Keep threads in standby mode or kill / restart them?

Pseudo-situation: have a class (say, BackgroundMagic), and it has methods Start()and Stop(). Work in this class is performed by one single thread and is just a short cycle every X milliseconds.

Which of these options is better, how much is needed to control the stop / start? It is impossible to decide which path to take.

  • The first call to Start () initializes and starts the stream with IsBackground= true. Use the simple bool flag to indicate on each cycle whether it should actually do any work or just sleep. After initial initialization, let Stop () and Start () simply control the bool flag. The thread will simply be stopped and cleared by the runtime, since IsBackground= true when the application exits.
  • Strongly interrupt / connect / interrupt / whatever Stop and re-create the thread in Start (), without leaving a thread around.

... or any better / cleaner ways to do this?

+3
source share
6 answers

None! Use Thread Pool!

+7

, " " - . , , Apache .

, , №1. , № 2 , .

+1

, , . /, , , /, .

+1

. , . TPL (Task Paralell Library) .NET 4.

, , , , , . Thread.Sleep , , , . () , , , , . AutoResetEvent. , , , . , , , .

, , - bool ( volatile ). , !

:

+1

bool, , . . bools , , , .

, , - Dispose .

0

bool, , , . :

while (true)
{
  if (shouldSleep)
 {
   Thread.Sleep(interval);
   continue;
 }

  doSomeWork();

 if (shouldCancel)
 {
   CleanUpResources();
   break;
 }
}

, , . , , . . , .

, , . , , . , .

0
source

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


All Articles