cornergraf
cornergraf

Reputation: 582

Will multiple Control.BeginInvoke/Invoke calls execute in order?

I need to know whether Control.BeginInvoke and Control.Invoke calls will execute in the order they are called.

I have the following scenario:

  1. UI thread is blocked
  2. WCF thread calls Control.BeginInvoke
  3. WCF thread calls Control.Invoke (or possibly BeginInvoke again)
  4. UI thread is unblocked
  5. ??

The execution order of step 1-4 is guaranteed to be in the shown order (technically the order is not guaranteed to be that way, but the question I have is only relevant if the order is as shown).

The question I have is whether there is any chance that the Invoke/BeginInvoke call in step 3 is executed before the BeginInvoke call in step 2?

Also, please don't comment on blocking the UI thread.

Upvotes: 16

Views: 4903

Answers (4)

rui
rui

Reputation: 11284

No chance you can assume that but if there's actual some form of dependency between the two calls above have them waiting on a semaphore and only execute the dependent code when they're both completed.

If the reason why you're making the two calls at the same time is not performance then I would probably just execute the second call in the callback of the first (makes it a lot easier to debug).

Upvotes: 0

Jeff Cyr
Jeff Cyr

Reputation: 4864

In your case, step 2 will always execute before step 3. BeginInvoke on the UI thread will execute in the order it has been queued.

The UI thread is in fact a message pump, it has a single message queue with only one thread consuming it, so it's guaranteed that work items will be executed in the order they were queued.

It's with Delegate.BeginInvoke that the order of execution may be non-sequential.

Upvotes: 12

Laurent Etiemble
Laurent Etiemble

Reputation: 27929

BeginInvoke calls are queued on the destination thread (as they are posted in order of arrival).

Synchronous calls on the WCF Thread (step 3) may be executed before asynchronous calls (step 2) made from this thread.

Upvotes: 3

Greg D
Greg D

Reputation: 44096

Not enough information to give you a good answer. The UI thread is blocked so steps 2 and 3 must be running on a different thread. If there's no synchronization between the two, then how could we know any ordering?

Thread 1        Thread 2                       Thread 3         Thread 4
Block UI        Calls BeginInvoke              
Unblock UI      Calls Invoke or BeginInvoke    BeginInvoke runs  BeginInvoke runs

You've got a lot a parallelism going on, but from what you've described, there's no possible way we could tell you what possible orderings will occur, short of saying, "Anything." We can't even tell you that the calls to BeginInvoke won't happen before the UI thread is blocked or after the UI thread is unblocked.

Upvotes: 0

Related Questions