Custom MessageLoop

  • Thread starter Thread starter Marc ENGEL
  • Start date Start date
M

Marc ENGEL

Hi all,

I need to implement a Custom Message Loop in my
application.

Instead of calling Application.Run(), I'd like to do it by
myself calling:
while (true)
{
Application.DoEvents()
}

The problem is that when calling this function in a loop,
it will take all the CPU.

In the following thread, the better suggested solution is
to add a Sleep(55):
http://groups.google.com/groups?hl=fr&lr=&ie=UTF-8&oe=UTF-
8&selm=%23AqyL4oBDHA.2208%40TK2MSFTNGP12.phx.gbl

Is there no better solution using a function like
Application.WaitForEvent() that would wait for an event
before triggering the DoEvents:

while (true)
{
Application.WaitForEvent() 'This is the missing function
Application.DoEvents()
}

Maybe I'm old fashion but the Sleep-like solution looks
like polling and should not be used in a multi-threaded
application. Shouldn't there be some synchronisation
function provided by the framework?

Actually by looking at IL from Application.Run() it seems
that something exist but I don't know how to acces this
feature.
Something like:
System.Windows.Forms.Application/ThreadContext::LocalModalM
essageLoop(...)
that finally call the brave old:
PeekMessage and PreProcessMessage

Can I call this? Is it Unsafe?

Your advices are welcome,

Marc
 
Hi Marc,
How you said DoEvents calls PeekMessage that's way the UI thread is not
blocked if there is no messages in the queue. And the loop will eat up all
your processor time.
Why don't you just override Control.PreProcessMessage. I haven't teseted,
but if you return true from this method it seems like the control won't
perform any further processing of the message afterwards. Not all events
goes through windows message queue. In future there might be no message
queue at all so I strongly believe that skipping the normal Application.Run
is unsafe.

HTH
B\rgds
100
 
There's no such method in .NET. If you really want PeekMessage, you need to
PInvoke it.

In the Managed DirectX sample applications (included in the DirectX 9 SDK),
we also used the DoEvents / Sleep approach to build a custom message loop.
If you are interested, you can take a look at
sdkroot\Samples\C#\Common\D3DApp.cs.

The UnsafeNativeMethods.PeekMessage you saw in the IL code is not exposed
to applications. It is in a internal class and application can't access it.

Hope this helps.

Regards,
Xin

This posting is provided "AS IS" with no warranties, and confers no rights.

Are you secure? Visit http://windowsupdate.microsoft.com to get the latest
critical updates and service packs available for your computer's Windows
operating system.
 
Back
Top