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

烈酒焚心 提交于 2019-12-04 16:03:48

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.

So fire an event :-P

You could also look at using an AutoResetEvent:
http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx

What I do in this instance is get the WorkerThread to call a function after it has completed the work, which will invoke the the UI Thread, which can do the work in which you require.

E.g.

private void SetWorkerThreadToDoWork()
{
  WorkerThread.Start();
}

private void MyWorkerThreadWork()
{
  //This will be on the WorkerThread (called from WorkerThread.Start())
  DoWorkFunc();
  WorkComplete();
}

private void WorkComplete()
{
  if(InvokeRequired == true)
  {
    //Do the invoke
  }
  else
  {
  //Check work done by worker thread
  //e.g. ServersSqlDataSourceEnumerator.Instance.GetDataSources();
  }
}

If it's a simple process you're using, I'd go for a BackgroundWorkerThread, this comes with it's own events that are fired when work is complete. But if you require to use a Thread, I would either look in to Asynchronous Callbacks or a similar route to that shown above.

Rashmi Pandit

You can check my answer on this SO thread

It uses a call back mechanism. When the async operation is done, it will fire the callback method where you can handle the processing that needs to be done post SQL execution.

Use a similar approach to be notified when the asynchronous operation is done.

Hope this helps :)

I don't program in C# but here's what I did with Delphi, maybe you can do it as well with C#. I have a TThread descendant, and in the "destroy" event I send a message to its creator saying "hey I'm about to die !". This way its parent (which is the main thread) creates a new one if it needs a new one. To be precise it launches a timer that, when fired, creates a new thread if a new one is needed (sites sucking time (lol) !!).

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