Search code examples
c#.netmultithreadingworker-thread

How can I tell if a thread is finished executing without polling ThreadState?


Is there an elegant way to know when a worker thread is done executing so I can access resources it produced?

For example if the worker thread queried a list of SQL Servers using

ServersSqlDataSourceEnumerator.Instance.GetDataSources();

and saved the result in a DataTable variable, what mechanism can I use to know when this DataTable variable has been populated/is available. I don't want to poll ThreadState; it would be ideal to fire an event when it's done so I can perform actions with the result.

Thanks!


Solution

  • You can use a callback mechanism or block on an event to know of completion of an Async operation. See this page for the Asychronous Programming Model in .net - you can call BeginInvoke on any delegate to perform the action in an Async manner.

    If you're using the BackgroundWorker type, you can subscribe to the RunWorkerCompleted event.