开发者

WPF-C# Synchronizing ThreadPool threads

I have a code design as follows. The GUI thread makes three ThreadPool.QueueUserWorkItem calls. The third call wa开发者_开发技巧its for the first 2 calls to finish using AutoResetEvents. However, when one of the two threads throw an exception, I want the third thread to end and the control to return to the GUI thread. Any ideas on how I can go about doing this?


What's wrong with setting the events not only when the threads finish but also when they throw an exception?


Just use one autoreset event which is set when either thread completes (either normally or with an exception). Have two integer variables (shared by all threads), threadCompletedNormallyCount and threadCompletedAbnormallyCount. When a thread completes it increments one of these two variables using Interlocked.Increment to indicate how it completed, then sets the event.

When the third thread awakes it can check these variables to see whether it needs to exit (i.e. both threads have completed normally or at least one abnormally, though what do you intend to do with the uncompleted thread in the latter case?). If only one thread has completed normally it should sleep again.


Why don't you use the Parallel Task Library to sync your threads and have the outcome run through the dispatcher thread by storing a ref to the dispatcher in one of your tasks then use Dispatcher.BeginInvoke to execute the last step on the UI thread?


I like the idea of using the Parallel Task Library. You can set a barrier to wait for the two threads to finish and a Cancel Token to easily cancel either or both. IMO, the PTL has better exception handling too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜