C# multi-thread concurrency [easy to understand and practice]

Create a thread

There are three ways to create and execute Task: Can take parameters

 public void testTask(string[] args)
        {
    
    
            //1.new方式实例化一个Task,需要通过Start方法启动
            Task task = new Task(() =>
            {
    
    
                Thread.Sleep(100);
                Console.WriteLine($"hello, task1的线程ID为{
      
      Thread.CurrentThread.ManagedThreadId}");
            });
            task.Start();

            //2.Task.Factory.StartNew(Action action)创建和启动一个Task
            Task task2 = Task.Factory.StartNew(() =>
            {
    
    
                Thread.Sleep(100);
                Console.WriteLine($"hello, task2的线程ID为{
      
       Thread.CurrentThread.ManagedThreadId}");
            });

            //3.Task.Run(Action action)将任务放在线程池队列,返回并启动一个Task
            Task task3 = Task.Run<string>(() =>
            {
    
    
                Thread.Sleep(100);
              return $"hello, task3的线程ID为{
      
       Thread.CurrentThread.ManagedThreadId}";
            });
            Console.WriteLine("执行主线程!");
            Console.ReadKey();
        }

Task's blocking method (Wait/WaitAll/WaitAny)

task.Wait() means waiting for the task to be executed, and its function is similar to thead.Join(); Task.WaitAll(Task[] tasks) means to unblock only after all tasks have been executed; Task.WaitAny(Task[]
tasks ) means that the blocking will be released as soon as one task is executed.

//阻塞主线程。task1,task2都执行完毕再执行主线程
            //执行【task1.Wait();task2.Wait();】可以实现相同功能
            Task.WaitAll(new Task[] {
    
     taskwait1, taskwait2 });

After use, the current thread blocks and waits for the used thread to end.
 If WaitAll is replaced by WaitAny, then the thread blocking will be unblocked after any task is executed. What is the execution result?

Task continuation operation (WhenAny/WhenAll/ContinueWith)

//task1,task2执行完了后执行后续操作
            Task.WhenAll(task, task2).ContinueWith((t) =>
            {
    
    
                Thread.Sleep(100);
                Console.WriteLine("执行后续操作完毕!");
            });

            //通过TaskFactroy实现   等待完成后执行后续的线程
            Task.Factory.ContinueWhenAll(new Task[] {
    
     task, task2 }, (t) =>
             {
    
    
                 Console.WriteLine($"hello, task ContinueWhenAll的线程ID为{
      
      Thread.CurrentThread.ManagedThreadId}");
             });

Task cancellation (CancellationTokenSource)

Guess you like

Origin blog.csdn.net/qq_43886548/article/details/131105608