1

In WPF, I can push a message loop using Dispatcher.PushFrame.

What is the equivalent in WinForms? I'm familiar with DoEvents but that must be called in a loop which can spin the CPU instead of the very efficient approach of just waiting for a message or for an event to signal to exit (like Dispatcher.PushFrame has).

Andrew Arnott
  • 80,040
  • 26
  • 132
  • 171

2 Answers2

1

I was able to include WindowsBase to my project's references and just use Dispatcher.PushFrame and frame.Continue = false as usual.

Any caveats with wpf-winforms interop apply, and it does require part of wpf to be referenced, but it should still be better than DoEvents (which has severe pitfalls).

secondperson
  • 148
  • 1
  • 4
-1

This is the equivalent:

        System.Threading.SendOrPostCallback callback = o =>
        {
            this.Text = "Hello" + o.ToString(); // "Hello42"
        };
        WindowsFormsSynchronizationContext.Current.Post(callback, 42);

The 42 is a state parameter that gets past to the callback.

You can also do this:

        this.BeginInvoke((Action)(() => this.Text = "Hello"));

BTW, you should never ever ever use DoEvents - it's a great way to introduce bugs in to your code and is really only there for VB6 compatibility.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • No, that's not the equivalent. That's just posting a message. My question is how to push a message loop that would process such a message. I agree on `DoEvents` being exceptionally problematic and I avoid it like the plague. Nevertheless, for this unit test I'm writing, I don't need to worry about stray messages being processed and I do need to simulate the UI thread processing events since there in fact is *no* main message loop in my unit test. – Andrew Arnott Feb 06 '16 at 15:36