Reputation: 4979
Is it possible to give callback(announcing completion of activity) for threads created using Thread class. I have created the thread the following way but could not find a way to give the callback.
Thread thread = new Thread(StartPoll);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Upvotes: 4
Views: 2164
Reputation: 941545
Setting the apartment state to STA is not enough, the second requirement is that you must pump a message loop. Application.Run() in either Winforms or WPF. It is actually the message loop that permits marshaling a call to a specific thread. Implemented by respectively Control.Begin/Invoke and Dispatcher.Begin/Invoke().
That's however more of a UI implementation detail. The generic solution is very similar to what the UI thread does, you use a thread-safe queue and a loop in the "main" thread to read objects from the queue. Like a delegate you can invoke. A standard solution to the producer/consumer problem. The .NET 4 BlockingCollection class makes it easy. Rewriting the thread code so it loops and stays responsive to worker requests is not always so easy.
Upvotes: 3
Reputation: 244807
Not directly. But you can always do something like:
new Thread(() => { StartPoll(); Callback(); })
Upvotes: 5