How to restart Thread in C # .Net 4.0?

I am using C # .Net4.0 in VS 2010. How to restart Thread ?

As if I want Abort() thread and Start() it from the very beginning again? Is it possible?

+6
source share
5 answers

create a new stream instance and execute it again. thread1 = new Thread (); thread1.start ();

+7
source

Interrupting a stream is often a bad idea. He is an adviser. If it is an infinite loop, a boolean value is used to stop the flow without abortion.

 bool run = true; Thread thread = new Thread(method); thread.start(); private void method() { while(run) { } } 

To stop the thread, just set the boolean value to false and, as a rule, you can restart it later.

+7
source

Thread.Abort does not guarantee that the thread will terminate. For example, if you have a long request, Abort will not stop the request or cancel the stream. In fact, the thread will run until the request completes.

If you do everything in managed code and are not locked by unmanaged resources, and you must interrupt the thread, thread.Abort () works fine.

However, you cannot invoke Start on a thread that has been interrupted. You will need to create another thread and call "Start" in this thread. Creating a theme is somewhat more expensive, the memory is reasonable in .NET (compared to other langauges), so there are some disadvantages.

+2
source

If you want to restart the stream from the very beginning, you really want to restart the execution of a certain function (code stream) in the stream. When you create a thread and pass the function to execute, the life of the thread will end as soon as the function completes its execution. You just need to change the design of the code, which will allow you to restart the function with the recreation of a new thread. But for short functions, I would recommend using ThreadPool .

+1
source

Since you are using .NET 4.0, where MS introduced the "Cooperative revocation system." You can learn more from this blog . Turning directly to Thread (more and more) is discouraged.

+1
source

Source: https://habr.com/ru/post/910063/


All Articles