Is it possible to group/isolate tasks in ThreadPool when using WaitHandle.WaitAll?

耗尽温柔 提交于 2019-12-24 00:35:32

问题


The scenario I am facing is as below. Because ThreadPool is 1 instance per process so my question is that would method 1 cancel tasks queued by method 2 after 3 seconds?

http request comes in

*method 1 gets executed first*:

  ThreadPool.QueueUserWorkItem x 3
  WaitHandle.WaitAll for 3 seconds

*method 2 gets executed after method 1*:

  ThreadPool.QueueUserWorkItem x 10
  WaitHandle.WaitAll for 10 seconds

Sorry I think I totally misunderstood the use of WaitHandle. It seems that if I do below everything will work as desired. So sorry for the confusion.

var calls = new ManualResetEvent[5];
//ThreadPool.QueueUserWorkItem blah...
WaitHandle.WaitAll(calls, timeOut);

But I am still thinking what will happen when method 1 flooded thread pool with long running tasks and method 2 only waits for 1 second. Will method 2 ever get its results back because it's not waiting long enough.

Thanks.


回答1:


No, it wouldn't cancel the tasks. Simply you'd rather stop waiting. BTW, wouldn't rather an timeout exception be thrown when WaitAll exceeds timeout?




回答2:


I think, you should create your own queue+dispatcher to process a group your actions or tasks. The Active Object pattern is a good choose. You can control priority of execution of actions, can write the rule to wait some actions in group (by using Guard method), wait for "any" or "all" results. You can read this article, it has code to try this pattern in action.

Luck!




回答3:


As other people have pointed out, when the wait is complete method 1 will not cancel the threads queued by method 2 unless you have some explicit code in method 1 that specifically cause method 2 to cancel.

You mentioned that you might have a race condition, but unless method 2 is relying on method 1 to complete in order to do some computation with the results in method 1, then there is no apparent race condition in your example.

Please clarify where you think you're seeing a race condition and why, from your current example it doesn't seem like you have a race condition.




回答4:


In reference to your update:

Be aware if you're using WaitAll with a windows forms application that it will not work without setting your entry point to [MTAThread] (which the compiler fails on anyway).

This enhanced ThreadPool supports grouping of work items (and cancelling them) which may help if you're still looking for a solution.



来源:https://stackoverflow.com/questions/2322557/is-it-possible-to-group-isolate-tasks-in-threadpool-when-using-waithandle-waital

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!