开发者

Dispatcher.Invoke hangs when the main thread called Thread.Join

I am having a problem, for which I am not able 开发者_C百科to find a solution. The problem is as follows:

In the main thread (the default thread), I am starting a thread and then immediately in the main thread, I wait for the thread's exit by calling Thread.Join on the spawned thread. When I do that if the spawned thread tries to callback in the main thread's context by calling Dispatcher.Invoke, it hangs. Any ideas how I can allow the callback?

The callback has the logic to signal the thread to exit. Without executing the callback, the thread will never exit, and so the main thread is also stuck.


What's the point of starting a new thread if you just wait for it to complete ? Just do the work on the main thread...


I'm not exactly sure what you are asking but you may try BeginInvoke instead of Invoke


If you're only going to be waiting on the thread to terminate, you could simply have a polling loop, like this:

// var otherThread = ...;
volatile bool terminate = false;

while (!terminate)
{
    Thread.Sleep(100);
}
otherThread.Join();

Then, leave it up to the callbacks to set the terminate flag to true once you're ready to join.


I had a similar problem which I finally solved in this way:

do{
    // Force the dispatcher to run the queued operations 
    Dispatcher.CurrentDispatcher.Invoke(delegate { }, DispatcherPriority.ContextIdle);
}while(!otherthread.Join(1));

This produces a Join that doesn't block because of GUI-operations on the other thread.

The main trick here is the blocking Invoke with an empty delegate (no-operation), but with a priority setting that is less than all other items in the queue. That forces the dispatcher to work through the entire queue. (The default priority is DispatcherPriority.Normal = 9, so my DispatcherPriority.ContextIdle = 3 is well under.)

The Join() call uses a 1 ms time out, and re-empties the dispatcher queue as long as the join isn't successful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜