Detecting that WorkPlayer ThreadPool has completed / pending completion

For some reason, ThreadPool QueueWorkItem does not return an IAsyncResult or any other work item descriptor, which allows it to wait until completion. There are RegisterWait... methods, but you have to go through WaitHandle , and creating them is expensive (see IAsyncResult Documentation, which recommends deferring WaitHandle creation until requested). A parallel task library will eliminate this shortcoming, but there is a long wait for it. So, are there any problems with this design:

 public class Concurrent<T> { private ManualResetEvent _resetEvent; private T _result; public Concurrent(Func<T> f) { ThreadPool.QueueUserWorkItem(_ => { _result = f(); if (_resetEvent != null) _resetEvent.Set(); }); } public WaitHandle WaitHandle { get { if (_resetEvent == null) _resetEvent = new ManualResetEvent(_result != null); return _resetEvent; } ... 

EDIT: I asked a question about the problems encountered when using async delegates instead of ThreadPool .

+4
multithreading c # asynchronous concurrency threadpool
source share
2 answers

Well, you have a race condition between getting WaitHandle and tuning. Do you really want the caller to wait forever if they are a little late?

You should probably lock accordingly and keep the β€œI'm done” flag so that if you create WaitHandle after it finishes, you set it before returning it.

I also personally wrote a static factory method instead of just using a public constructor, or creating a create, then explicitly run template. The work item queue in the constructor seems strange to me.

+6
source share

Why aren't you using an asynchronous delegate, as shown here:

http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx

That would make Concurrent obsolete, no?

+3
source share

All Articles