How to stop one thread when another ends

I have this code

        Thread thread1 = new Thread(this.DoSomething1);
        Thread thread2 = new Thread(this.DoSomething2);
        thread1.Start();
        thread2.Start();

I need the first thread that ends to kill another immediately. Note that the thread is not the one that is running at the time, so I cannot use a static variable telling the thread to stop. Which thread ends first?

+4
source share
4 answers

Ideally, you want to use a cancel marker or static variable to safely cancel the stream.


If you decide to use the cancelationToken / tokenSource file:

  var tokenSource = new CancellationTokenSource();
  var token = tokenSource.Token;

  ...

  static void DoSomething1or2(CancellationToken token, CancellationTokenSource tokenSource)
  {

      //Do other work here

      //Since you said neither of your tasks were looping, just put this where
      //you'd want to cancel the thread
      if(token.IsCancellationRequested)
        return; // or token.ThrowIfCancellationRequested();

      //do some more stuff here

      tokenSource.IsCancellationRequested = true;
  }

doSomething , , , . cancelationToken.

if(otherThreadIsActive && originalCondition)
   {
       //do stuff here
   }

, . , .


: /tokenSource

: - , ,

+4

Thread " , ". , , , , , Task.Run, Thread. , CancellationTokenSource.

var cts = new [] {
    new CancellationTokenSource(),
    new CancellationTokenSource()};
var ts = new[]
{
    Task.Run(() => DoSomething1(cts[0].Token), cts[0].Token),
    Task.Run(() => DoSomething2(cts[1].Token), cts[1].Token)
};

var w = Task.WaitAny(ts);
for (int i = 0; i < cts.Length; i++)
{
    if (i != w) cts[i].Cancel();
}

DoSomething CancellationToken.IsCancellationRequested . Task.Run, , , . .

+1

, . for for, , . ( - ), -.

0

What I did in the past when I synchronize thread invalidation has a static event in the class that rotates threads. These threads perform the functions of different classes that all listen to this static event. When this event fires, the parameter is volatile private bool _aboutRequestedset to true, which is located in the thread-sweep execution class. During the thread execution loop, the last thing to do is check this request requested by bool, and if true, exit gracefully.

0
source

All Articles