简体   繁体   中英

How to restart a Thread in C# .Net 4.0?

I'm using C# .Net4.0 in VS 2010. How do I restart a Thread ?

Its like I want to Abort() the thread and Start() it from the beginning again? Is it possible?

Abort a thread is often a bad idea. He is an advisor. If it's an infinite loop, a boolean used to stop the thread without the abortion.

bool run = true;
Thread thread = new Thread(method);
thread.start();

private void method()
{
  while(run)
  {

  }
}

To stop the thread, just set the boolean to false and normally, you can restart it later.

create new instance of thread and execute again. thread1= new Thread(); thread1.start();

Thread.Abort does not guarantee that the thread will terminate. For instance, if you have a long running query, Abort will not terminate the execution of the query, or the cancellation of the thread. In fact, the thread will live on until the query completes.

If you're doing everything in managed code and not getting locked up by unmanaged resources, and you must abort a thread, thread.Abort() is perfectly fine.

However, you cannot call Start on a thread that has been terminated. You'll have to create another Thread and call Start on that thread. Thread creation is somewhat expensive, memory wise, in .NET (in comparison with other langauges), so there are some drawbacks.

When you want to re-start the thread from the beginning, you actually want to restart an execution of certain function (code flow) on the thread. When you create a thread and pass a function for execution, a thread's life will be terminated as soon as the function finishes its own execution. You just need to change your code design that will allow to restart the function with recreating a new thread. But for short functions I would advise to use ThreadPool .

Since you are using .NET 4.0, where MS had introduced the "Cooperative Cancellation Framework". You can read more from this blog . Dealing directly with Thread is (more and more) discouraged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM