zoukankan      html  css  js  c++  java
  • Task

    .net 4.0为我们带来了TPL(Task Parallel Library),其中Task相较ThreadPool线程池使用更简单,而且支持线程的取消,完成和失败通知等交互性操作,而这些是ThreadPool所没有的。并且Task是可以有返回值的。

    传参

    给异步方法传参,可以使用以下几种方法。

      1 new Thread(Go1).Start("arg1");//最原始的传参
      2             new Thread(delegate() //使用匿名委托传参
      3                 {
      4                     Go1("arg1");
      5                 }).Start();
      6             new Thread(() => //使用lambda表达式
      7                 {
      8                     Go1("arg1");
      9                 }).Start();
    View Code

    可以有返回值

    Thread和ThreadPool都不能有返回值,但Task是可以有返回值的。

      1 var result = Task.Factory.StartNew<string>(() =>
      2             {
      3                 return Go1("arg1");
      4             });
    View Code

    Demo

    上代码。

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Threading;
      6 using System.Threading.Tasks;
      7 
      8 namespace AsyncCoding
      9 {
     10     class Program
     11     {
     12         static void Main(string[] args)
     13         {
     14             Task.Factory.StartNew(() => //Task默认创建的都是后台线程
     15             {
     16                 Go1("arg1");
     17             });
     18 
     19             Console.WriteLine("我是主线程,Thread Id:{0}", Thread.CurrentThread.ManagedThreadId);
     20             Console.ReadKey();
     21         }
     22 
     23         public static void Go1(string input)
     24         {
     25             Console.WriteLine("我是异步线程,Thread Id:{0},是否为后台线程:{1}, 传入参数为:{2}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsBackground, input);
     26             for (int i = 0; i < 10; i++)
     27             {
     28                 Thread.Sleep(100);//模拟每次执行需要100ms
     29                 Console.WriteLine("异步线程,Thread Id:{0},运行:{1}", Thread.CurrentThread.ManagedThreadId, i);
     30             }
     31         }
     32     }
     33 }
     34 
    View Code

    代码执行顺序图解。

    2016-07-08_173957

    运行结果如下图。

    image

  • 相关阅读:
    bzoj 2969: 矩形粉刷 概率期望+快速幂
    loj #6191. 「美团 CodeM 复赛」配对游戏 期望dp
    CF446C DZY Loves Fibonacci Numbers 线段树 + 数学
    CF696B Puzzles 概率期望
    bzoj 3566: [SHOI2014]概率充电器 数学期望+换根dp
    loj #6342. 跳一跳 期望dp
    CF316G3 Good Substrings 广义后缀自动机
    bzoj 3829: [Poi2014]FarmCraft 树形dp+贪心
    bzoj 2131: 免费的馅饼
    CF19D Points 平衡树
  • 原文地址:https://www.cnblogs.com/mcgrady/p/5654186.html
Copyright © 2011-2022 走看看