• Task多线程


    Task多线程

     1.首先是我们线程之间的启动。

     1.这样

        Task task = new Task(()=>
                {
                    //
                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("do something....");
                    //匿名函数,
                    //还要其他的一些东邪;
                });
                task.Start();

    2.或则这样

     Task t=Task.Run(()=> { Console.WriteLine("直接我就开始run了..."); });

    3.再或则这样

      static void DoSomething()
            {
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("do something..static");
    
            }
            static void Main(string[] args)
            {
                Task t1 = new Task(DoSomething);
                t1.Start(); //这样我们就启动的落地呀;
    
                
                Console.WriteLine("I am main thread line");
                Console.ReadLine();
            }

    4.这样

      Task task = Task.Factory.StartNew(() => { Console.WriteLine("这样,直接使用的Task.Factory.StartNew"); });
      TaskFactory tf = new TaskFactory();
      Task t1 = tf.StartNew(() => { Console.WriteLine("再或则这样..."); });

    总结:大概就是两种方式;构造函数和我们的factory;

    1.等待任务的完成并获取返回值,这个就是我们简单的基本操作;

                Task<int> task = new Task<int>(() => {
                    int sum = 0;
                    Console.WriteLine("fucking life...");
                    for (int i = 0; i < 100; i++)
                    {
                        sum += i;
                    }
                    return sum;
                });
                task.Start();
                task.Wait();
                var result = task.Result.ToString();
                Console.WriteLine("result is "+task.Result.ToString());
                Console.WriteLine("I am main thread line");
                Console.ReadLine();

    2.ContinueWith方法在任务完成时启动一个新任务

     Task<int> task = new Task<int>(() => {
                    System.Threading.Thread.Sleep(600);
                    int sum = 0;
                    Console.WriteLine("fucking life...");
                    for (int i = 0; i < 100; i++)
                    {
                        sum += i;
                    }
                    return sum;
                });
                task.Start();
                Console.WriteLine("主线程,执行其他任务...");
                
                Task hoop=task.ContinueWith(t=>{
                    Console.WriteLine("任务执行完之后的结果是:{0}",t.Result.ToString());
                });
    
                Console.WriteLine("I am main thread line");
                Console.ReadLine();

    Task 的生命周期;

                var task1 = new Task(() =>
                  {
                      Console.WriteLine("begin");
                      System.Threading.Thread.Sleep(2000);
                      Console.WriteLine("finish");
    
                  });
                Console.WriteLine("before start:"+task1.Status);
                task1.Start();
                Console.WriteLine("after start:"+task1.Status);
                task1.Wait();  //用来主阻塞线程,
                Console.WriteLine("after finissh:"+task1.Status);

    从我们可以得出Task的简略生命周期:

    Created:表示默认初始化任务,但是“工厂创建的”实例直接跳过。

    WaitingToRun: 这种状态表示等待任务调度器分配线程给任务执行。

    RanToCompletion:任务执行完毕。

    Task 流程的控制

     var task1 = new Task(() =>
                  {
                      Console.WriteLine("task 1 begin");
                      System.Threading.Thread.Sleep(2000);
                      Console.WriteLine("task 1 finished");
                  });
    
                var task2 = new Task(() =>
                {
                    Console.WriteLine("task 2 begin");
                    System.Threading.Thread.Sleep(2000);
                    Console.WriteLine("task 2 finished");
                });
    
    
                var task3 = new Task(() =>
                {
                    Console.WriteLine("task 3 begin");
                    System.Threading.Thread.Sleep(2000);
                    Console.WriteLine("task 3 finished");
                });
    
                task1.Start();
                task2.Start();
                task3.Start();
    
                Task.WaitAll(task1, task2, task3);  //他它接受数组类型的task的使用地呀;
                Console.WriteLine("All task has finished");
    
    
                Console.ReadLine();

     Ps: Task.WaitAny

    这个用发同Task.WaitAll,就是等待任何一个任务完成就继续向下执行,将上面的代码WaitAll替换为WaitAny,输出结果如下:

     ContinueWith的用法。

                var task1 = new Task(() =>
                  {
                      Console.WriteLine("task 1 begin");
                      System.Threading.Thread.Sleep(500);
                      Console.WriteLine("task 1 finished");
                  });
    
    
                task1.Start();
                var result = task1.ContinueWith<string>(t=> {
    
                    Console.WriteLine("task1 finished ");
                    return "continue task finish.....";
                });
    //在每次调用ContinueWith方法时,每次会把上次Task的引用传入进来,以便检测上次Task的状态,
                var send = Task.Factory.StartNew(() => { Console.WriteLine("fuck life.."); })
                    .ContinueWith<bool>(s => { if (1 == 1) return false; })
                    .ContinueWith<string>(r =>
                    {
                        if (r.Result)
                        {
                            return "Finished";  //可以获取上一个流程task 中的值
                        }
                        else
                        {
                            return "Error";
                        }
    
                    });
                Console.WriteLine(send.Result);
    
                

    Task的取消

        

    var tokenSource = new CancellationTokenSource();
                var token = tokenSource.Token;
                Console.WriteLine(token.ToString());
    
                var task = Task.Factory.StartNew(() =>
                  {
                      for (var i = 0; i < 1000; i++)
                      {
                          System.Threading.Thread.Sleep(1000);
                          Console.WriteLine("proceeed mission...");
                          if (token.IsCancellationRequested)
                          {
                              Console.WriteLine("Abort mssion sucess!");
                              //这里也采用轮循的方式....
                              return;
                          }
                      }
    
                  },token);
    
                token.Register(() =>
                {
                    Console.WriteLine("Cancle task....");
                });
    
                Console.WriteLine("press enter to cancle task...");
                Console.ReadKey();
                tokenSource.Cancel();
    
                Console.ReadLine();

     这里还有一篇较好的文章:http://www.cnblogs.com/jesse2013/p/async-and-await.html

  • 相关阅读:
    关于java中的批注@SuppressWarnings
    Enumeration接口的用法
    java中的Properties类的操作
    编译java时出现(端口冲突)Address already in use: JVM_Bind<null>:1919
    jQuery画廊插件-GalleryView
    jQuery中用attr和prop获取checkbox的属性问题
    (报错记录)Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:
    JDK 和 JRE 的区别(转载)
    css属性之vertical-align详解
    this——笔记
  • 原文地址:https://www.cnblogs.com/mc67/p/5897864.html
Copyright © 2020-2023  润新知