c#Task多线程停止

c#Task

    • 线程创建
    • 线程停止

线程创建

using System.Threading;

CancellationTokenSource cancelTokenSource 
= new CancellationTokenSource();

 Task t1 = Task.Factory.StartNew(
    delegate
    { while (!cancelTokenSource.IsCancellationRequested)
                   {
                       Thread.Sleep(500);
                       Console.WriteLine("111:");
                   }
     }, cancelTokenSource);
     
  Task t2 = Task.Factory.StartNew(
  delegate
   {while (!cancelTokenSource.IsCancellationRequested)
                   {
                       Thread.Sleep(500);
                       Console.WriteLine("222:");
                   }
               }, cancelTokenSource);
               
  Task t3 = Task.Factory.StartNew(
  delegate
  { while (!cancelTokenSource.IsCancellationRequested)
                   {
                       Thread.Sleep(500);
                       Console.WriteLine("333:");
                   }
               }, cancelTokenSource);

线程停止

 cancelTokenSource.Cancel();

你可能感兴趣的:(c#,开发语言)