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

  • 相关阅读:
    今天面试一些程序员(新,老)手的体会
    UVA 10635 Prince and Princess
    poj 2240 Arbitrage
    poj 2253 Frogger
    poj 2485 Highways
    UVA 11258 String Partition
    UVA 11151 Longest Palindrome
    poj 1125 Stockbroker Grapevine
    poj 1789 Truck History
    poj 3259 Wormholes
  • 原文地址:https://www.cnblogs.com/mcgrady/p/5654186.html
Copyright © 2011-2022 走看看