深入分析C# Task

​Task的MSDN的描述如下:

【Task类的表示单个操作不会返回一个值,通常以异步方式执行。

Task对象是一种的中心思想基于任务的异步模式首次引入.NETFramework 4 中。

因为由执行工作Task对象通常以异步方式执行线程池线程上而不是以同步方式在主应用程序线程中,可以使用Status属性,并将IsCanceled, IsCompleted,和IsFaulted属性,以确定任务的状态。

大多数情况下,lambda 表达式用于指定该任务所执行的工作量。

对于返回值的操作,您使用Task类。】

1、Task的优势

  ThreadPool相比Thread来说具备了很多优势,但是ThreadPool却又存在一些使用上的不方便。比如:

  • ThreadPool不支持线程的取消、完成、失败通知等交互性操作;
  • ThreadPool不支持线程执行的先后次序;

  以往,如果开发者要实现上述功能,需要完成很多额外的工作,现在,FCL中提供了一个功能更强大的概念:Task。Task在线程池的基础上进行了优化,并提供了更多的API。在FCL4.0中,如果我们要编写多线程程序,Task显然已经优于传统的方式。

  以下是一个简单的任务示例:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static void Main(string[] args)
    {
      Task t = new Task(() =>
      {
        Console.WriteLine("任务开始工作……");
        //模拟工作过程
        Thread.Sleep(5000);
      });
      t.Start();
      t.ContinueWith((task) =>
      {
        Console.WriteLine("任务完成,完成时候的状态为:");
        Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
      });
      Console.ReadKey();
    }
  }
}

2、Task的用法

  2.1、创建任务

  (一)无返回值的方式

  方式1:

  var t1 = new Task(() => TaskMethod("Task 1"));
  t1.Start();
  Task.WaitAll(t1);//等待所有任务结束
  注:任务的状态:
  Start之前为:Created
  Start之后为:WaitingToRun 

  方式2:

Task.Run(() => TaskMethod("Task 2"));

  方式3:

Task.Factory.StartNew(() => TaskMethod("Task 3")); 直接异步的方法
  //或者
  var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
  Task.WaitAll(t3);//等待所有任务结束
  //任务的状态:
  Start之前为:Running
  Start之后为:Running
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static void Main(string[] args)
    {
      var t1 = new Task(() => TaskMethod("Task 1"));
      var t2 = new Task(() => TaskMethod("Task 2"));
      t2.Start();
      t1.Start();
      Task.WaitAll(t1, t2);
      Task.Run(() => TaskMethod("Task 3"));
      Task.Factory.StartNew(() => TaskMethod("Task 4"));
      //标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。
      Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);

      #region 常规的使用方式
      Console.WriteLine("主线程执行业务处理.");
      //创建任务
      Task task = new Task(() =>
      {
        Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
        for (int i = 0; i < 10; i++)
        {
          Console.WriteLine(i);
        }
      });
      //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
      task.Start();
      Console.WriteLine("主线程执行其他处理");
      task.Wait();
      #endregion

      Thread.Sleep(TimeSpan.FromSeconds(1));
      Console.ReadLine();
    }

    static void TaskMethod(string name)
    {
      Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
        name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
    }
  }
}

  async/await的实现方式:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    async static void AsyncFunction()
    {
      await Task.Delay(1);
      Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
      for (int i = 0; i < 10; i++)
      {
        Console.WriteLine(string.Format("AsyncFunction:i={0}", i));
      }
    }

    public static void Main()
    {
      Console.WriteLine("主线程执行业务处理.");
      AsyncFunction();
      Console.WriteLine("主线程执行其他处理");
      for (int i = 0; i < 10; i++)
      {
        Console.WriteLine(string.Format("Main:i={0}", i));
      }
      Console.ReadLine();
    }
  }
}

  (二)带返回值的方式

  方式4:

Task<int> task = CreateTask("Task 1");
task.Start();
int result = task.Result;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static Task<int> CreateTask(string name)
    {
      return new Task<int>(() => TaskMethod(name));
    }

    static void Main(string[] args)
    {
      TaskMethod("Main Thread Task");
      Task<int> task = CreateTask("Task 1");
      task.Start();
      int result = task.Result;
      Console.WriteLine("Task 1 Result is: {0}", result);

      task = CreateTask("Task 2");
      //该任务会运行在主线程中
      task.RunSynchronously();
      result = task.Result;
      Console.WriteLine("Task 2 Result is: {0}", result);

      task = CreateTask("Task 3");
      Console.WriteLine(task.Status);
      task.Start();

      while (!task.IsCompleted)
      {
        Console.WriteLine(task.Status);
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
      }

      Console.WriteLine(task.Status);
      result = task.Result;
      Console.WriteLine("Task 3 Result is: {0}", result);

      #region 常规使用方式
      //创建任务
      Task<int> getsumtask = new Task<int>(() => Getsum());
      //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
      getsumtask.Start();
      Console.WriteLine("主线程执行其他处理");
      //等待任务的完成执行过程。
      getsumtask.Wait();
      //获得任务的执行结果
      Console.WriteLine("任务执行结果:{0}", getsumtask.Result.ToString());
      #endregion
    }

    static int TaskMethod(string name)
    {
      Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
        name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
      Thread.Sleep(TimeSpan.FromSeconds(2));
      return 42;
    }

    static int Getsum()
    {
      int sum = 0;
      Console.WriteLine("使用Task执行异步操作.");
      for (int i = 0; i < 100; i++)
      {
        sum += i;
      }
      return sum;
    }
  }
}

async/await的实现:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    public static void Main()
    {
      var ret1 = AsyncGetsum();
      Console.WriteLine("主线程执行其他处理");
      for (int i = 1; i <= 3; i++)
        Console.WriteLine("Call Main()");
      int result = ret1.Result;         //阻塞主线程
      Console.WriteLine("任务执行结果:{0}", result);
    }

    async static Task<int> AsyncGetsum()
    {
      await Task.Delay(1);
      int sum = 0;
      Console.WriteLine("使用Task执行异步操作.");
      for (int i = 0; i < 100; i++)
      {
        sum += i;
      }
      return sum;
    }
  }
}

  2.2、组合任务.ContinueWith

   简单Demo:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    public static void Main()
    {
      //创建一个任务
      Task<int> task = new Task<int>(() =>
      {
        int sum = 0;
        Console.WriteLine("使用Task执行异步操作.");
        for (int i = 0; i < 100; i++)
        {
          sum += i;
        }
        return sum;
      });
      //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
      task.Start();
      Console.WriteLine("主线程执行其他处理");
      //任务完成时执行处理。
      Task cwt = task.ContinueWith(t =>
      {
        Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());
      });
      task.Wait();
      cwt.Wait();
    }
  }
}

   任务的串行:

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static void Main(string[] args)
    {
      ConcurrentStack<int> stack = new ConcurrentStack<int>();

      //t1先串行
      var t1 = Task.Factory.StartNew(() =>
      {
        stack.Push(1);
        stack.Push(2);
      });

      //t2,t3并行执行
      var t2 = t1.ContinueWith(t =>
      {
        int result;
        stack.TryPop(out result);
        Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
      });

      //t2,t3并行执行
      var t3 = t1.ContinueWith(t =>
      {
        int result;
        stack.TryPop(out result);
        Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
      });

      //等待t2和t3执行完
      Task.WaitAll(t2, t3);

      //t7串行执行
      var t4 = Task.Factory.StartNew(() =>
      {
        Console.WriteLine("当前集合元素个数:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
      });
      t4.Wait();
    }
  }
}

  子任务:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    public static void Main()
    {
      Task<string[]> parent = new Task<string[]>(state =>
      {
        Console.WriteLine(state);
        string[] result = new string[2];
        //创建并启动子任务
        new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();
        new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();
        return result;
      }, "我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。");
      //任务处理完成后执行的操作
      parent.ContinueWith(t =>
      {
        Array.ForEach(t.Result, r => Console.WriteLine(r));
      });
      //启动父任务
      parent.Start();
      //等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束
      //parent.Wait();
      Console.ReadLine();

    }
  }
}

  动态并行(TaskCreationOptions.AttachedToParent) 父任务等待所有子任务完成后 整个任务才算完成

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Node
  {
    public Node Left { get; set; }
    public Node Right { get; set; }
    public string Text { get; set; }
  }

  class Program
  {
    static Node GetNode()
    {
      Node root = new Node
      {
        Left = new Node
        {
          Left = new Node
          {
            Text = "L-L"
          },
          Right = new Node
          {
            Text = "L-R"
          },
          Text = "L"
        },
        Right = new Node
        {
          Left = new Node
          {
            Text = "R-L"
          },
          Right = new Node
          {
            Text = "R-R"
          },
          Text = "R"
        },
        Text = "Root"
      };
      return root;
    }

    static void Main(string[] args)
    {
      Node root = GetNode();
      DisplayTree(root);
    }

    static void DisplayTree(Node root)
    {
      var task = Task.Factory.StartNew(() => DisplayNode(root),
                      CancellationToken.None,
                      TaskCreationOptions.None,
                      TaskScheduler.Default);
      task.Wait();
    }

    static void DisplayNode(Node current)
    {

      if (current.Left != null)
        Task.Factory.StartNew(() => DisplayNode(current.Left),
                      CancellationToken.None,
                      TaskCreationOptions.AttachedToParent,
                      TaskScheduler.Default);
      if (current.Right != null)
        Task.Factory.StartNew(() => DisplayNode(current.Right),
                      CancellationToken.None,
                      TaskCreationOptions.AttachedToParent,
                      TaskScheduler.Default);
      Console.WriteLine("当前节点的值为{0};处理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
    }
  }
}

  2.3、取消任务 CancellationTokenSource

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    private static int TaskMethod(string name, int seconds, CancellationToken token)
    {
      Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
        name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
      for (int i = 0; i < seconds; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        if (token.IsCancellationRequested) return -1;
      }
      return 42 * seconds;
    }

    private static void Main(string[] args)
    {
      var cts = new CancellationTokenSource();
      var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
      Console.WriteLine(longTask.Status);
      cts.Cancel();
      Console.WriteLine(longTask.Status);
      Console.WriteLine("First task has been cancelled before execution");
      cts = new CancellationTokenSource();
      longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
      longTask.Start();
      for (int i = 0; i < 5; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
        Console.WriteLine(longTask.Status);
      }
      cts.Cancel();
      for (int i = 0; i < 5; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
        Console.WriteLine(longTask.Status);
      }

      Console.WriteLine("A task has been completed with result {0}.", longTask.Result);
    }
  }
}

  2.4、处理任务中的异常

  单个任务:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static int TaskMethod(string name, int seconds)
    {
      Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
        name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
      Thread.Sleep(TimeSpan.FromSeconds(seconds));
      throw new Exception("Boom!");
      return 42 * seconds;
    }

    static void Main(string[] args)
    {
      try
      {
        Task<int> task = Task.Run(() => TaskMethod("Task 2", 2));
        int result = task.GetAwaiter().GetResult();
        Console.WriteLine("Result: {0}", result);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);
      }
      Console.WriteLine("----------------------------------------------");
      Console.WriteLine();
    }
  }
}

  多个任务:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static int TaskMethod(string name, int seconds)
    {
      Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
        name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
      Thread.Sleep(TimeSpan.FromSeconds(seconds));
      throw new Exception(string.Format("Task {0} Boom!", name));
      return 42 * seconds;
    }

    public static void Main(string[] args)
    {
      try
      {
        var t1 = new Task<int>(() => TaskMethod("Task 3", 3));
        var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
        var complexTask = Task.WhenAll(t1, t2);
        var exceptionHandler = complexTask.ContinueWith(t =>
            Console.WriteLine("Result: {0}", t.Result),
            TaskContinuationOptions.OnlyOnFaulted
          );
        t1.Start();
        t2.Start();
        Task.WaitAll(t1, t2);
      }
      catch (AggregateException ex)
      {
        ex.Handle(exception =>
        {
          Console.WriteLine(exception.Message);
          return true;
        });
      }
    }
  }
}

async/await的方式:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static async Task ThrowNotImplementedExceptionAsync()
    {
      throw new NotImplementedException();
    }

    static async Task ThrowInvalidOperationExceptionAsync()
    {
      throw new InvalidOperationException();
    }

    static async Task Normal()
    {
      await Fun();
    }

    static Task Fun()
    {
      return Task.Run(() =>
      {
        for (int i = 1; i <= 10; i++)
        {
          Console.WriteLine("i={0}", i);
          Thread.Sleep(200);
        }
      });
    }

    static async Task ObserveOneExceptionAsync()
    {
      var task1 = ThrowNotImplementedExceptionAsync();
      var task2 = ThrowInvalidOperationExceptionAsync();
      var task3 = Normal();

      try
      {
        //异步的方式
        Task allTasks = Task.WhenAll(task1, task2, task3);
        await allTasks;
        //同步的方式
        //Task.WaitAll(task1, task2, task3);
      }
      catch (NotImplementedException ex)
      {
        Console.WriteLine("task1 任务报错!");
      }
      catch (InvalidOperationException ex)
      {
        Console.WriteLine("task2 任务报错!");
      }
      catch (Exception ex)
      {
        Console.WriteLine("任务报错!");
      }

    }

    public static void Main()
    {
      Task task = ObserveOneExceptionAsync();
      Console.WriteLine("主线程继续运行........");
      task.Wait();
    }
  }
}

  2.5、Task.FromResult的应用

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static IDictionary<string, string> cache = new Dictionary<string, string>()
    {
      {"0001","A"},
      {"0002","B"},
      {"0003","C"},
      {"0004","D"},
      {"0005","E"},
      {"0006","F"},
    };

    public static void Main()
    {
      Task<string> task = GetValueFromCache("0006");
      Console.WriteLine("主程序继续执行。。。。");
      string result = task.Result;
      Console.WriteLine("result={0}", result);

    }

    private static Task<string> GetValueFromCache(string key)
    {
      Console.WriteLine("GetValueFromCache开始执行。。。。");
      string result = string.Empty;
      //Task.Delay(5000);
      Thread.Sleep(5000);
      Console.WriteLine("GetValueFromCache继续执行。。。。");
      if (cache.TryGetValue(key, out result))
      {
        return Task.FromResult(result);
      }
      return Task.FromResult("");
    }

  }
}

  2.6、使用IProgress实现异步编程的进程通知

  IProgress<in T>只提供了一个方法void Report(T value),通过Report方法把一个T类型的值报告给IProgress,然后IProgress<in T>的实现类Progress<in T>的构造函数接收类型为Action<T>的形参,通过这个委托让进度显示在UI界面中。

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    static void DoProcessing(IProgress<int> progress)
    {
      for (int i = 0; i <= 100; ++i)
      {
        Thread.Sleep(100);
        if (progress != null)
        {
          progress.Report(i);
        }
      }
    }

    static async Task Display()
    {
      //当前线程
      var progress = new Progress<int>(percent =>
      {
        Console.Clear();
        Console.Write("{0}%", percent);
      });
      //线程池线程
      await Task.Run(() => DoProcessing(progress));
      Console.WriteLine("");
      Console.WriteLine("结束");
    }

    public static void Main()
    {
      Task task = Display();
      task.Wait();
    }
  }
}

  2.7、Factory.FromAsync的应用 (简APM模式(委托)转换为任务)(BeginXXX和EndXXX)

  带回调方式的

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    private delegate string AsynchronousTask(string threadName);

    private static string Test(string threadName)
    {
      Console.WriteLine("Starting...");
      Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
      Thread.Sleep(TimeSpan.FromSeconds(2));
      Thread.CurrentThread.Name = threadName;
      return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
    }

    private static void Callback(IAsyncResult ar)
    {
      Console.WriteLine("Starting a callback...");
      Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
      Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
      Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
    }

    //执行的流程是 先执行Test--->Callback--->task.ContinueWith
    static void Main(string[] args)
    {
      AsynchronousTask d = Test;
      Console.WriteLine("Option 1");
      Task<string> task = Task<string>.Factory.FromAsync(
        d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

      task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}",
        t.Result));

      while (!task.IsCompleted)
      {
        Console.WriteLine(task.Status);
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
      }
      Console.WriteLine(task.Status);

    }
  }
}

  不带回调方式的

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
  class Program
  {
    private delegate string AsynchronousTask(string threadName);

    private static string Test(string threadName)
    {
      Console.WriteLine("Starting...");
      Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
      Thread.Sleep(TimeSpan.FromSeconds(2));
      Thread.CurrentThread.Name = threadName;
      return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
    }

    //执行的流程是 先执行Test--->task.ContinueWith
    static void Main(string[] args)
    {
      AsynchronousTask d = Test;
      Task<string> task = Task<string>.Factory.FromAsync(
        d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");
      task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
        t.Result));
      while (!task.IsCompleted)
      {
        Console.WriteLine(task.Status);
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
      }
      Console.WriteLine(task.Status);

    }
  }
}
//Task启动带参数和返回值的函数任务
//下面的例子test2 是个带参数和返回值的函数。

private int test2(object i)
{
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = true;
  }));
  System.Threading.Thread.Sleep(3000);
  MessageBox.Show("hello:" + i);
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = false;
  }));
  return 0;
}

//测试调用
private void call()
{
  //Func<string, string> funcOne = delegate(string s){ return "fff"; };
  object i = 55;
  var t = Task<int>.Factory.StartNew(new Func<object, int>(test2), i);
}

//= 下载网站源文件例子 == == == == == == == == == == == ==
//HttpClient 引用System.Net.Http
private async Task< int> test2(object i)
{
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = true;
  }));

  HttpClient client = new HttpClient();
  var a = await client.GetAsync("http://www.baidu.com");
  Task<string> s = a.Content.ReadAsStringAsync();
  MessageBox.Show (s.Result);

  //System.Threading.Thread.Sleep(3000);
  //MessageBox.Show("hello:"+ i);
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = false;
  }));
  return 0;
}

async private void call()
{
  //Func<string, string> funcOne = delegate(string s){ return "fff"; };
  object i = 55;
  var t = Task<Task<int>>.Factory.StartNew(new Func<object, Task<int>>(test2), i);
}

//----------或者----------

private async void test2()
{
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = true;
  }));
  HttpClient client = new HttpClient();
  var a = await client.GetAsync("http://www.baidu.com");
  Task<string> s = a.Content.ReadAsStringAsync();
  MessageBox.Show (s.Result);
  this.Invoke(new Action(() =>
  {
    pictureBox1.Visible = false;
  }));
}

private void call()
{
  var t = Task.Run(new Action(test2));
  //相当于
  //Thread th= new Thread(new ThreadStart(test2));
  //th.Start();
}

Task启动带参数和返回值的函数任务

以上就是深入分析C# Task的详细内容,更多关于C# Task的资料请关注我们其它相关文章!

(0)

相关推荐

  • C#线程处理系列之线程池中的I/O线程

    一.I/O线程实现对文件的异步  1.1  I/O线程介绍: 对于线程所执行的任务来说,可以把线程分为两种类型:工作者线程和I/O线程. 工作者线程用来完成一些计算的任务,在任务执行的过程中,需要CPU不间断地处理,所以,在工作者线程的执行过程中,CPU和线程的资源是充分利用的. I/O线程主要用来完成输入和输出的工作的,在这种情况下, 计算机需要I/O设备完成输入和输出的任务,在处理过程中,CPU是不需要参与处理过程的,此时正在运行的线程将处于等待状态,只有等任务完成后才会有事可做, 这样就造

  • c# 使用Task实现非阻塞式的I/O操作

    在前面的<基于任务的异步编程模式(TAP)>文章中讲述了.net 4.5框架下的异步操作自我实现方式,实际上,在.net 4.5中部分类已实现了异步封装.如在.net 4.5中,Stream类加入了Async方法,所以基于流的通信方式都可以实现异步操作. 1.异步读取文件数据 public static void TaskFromIOStreamAsync(string fileName) { int chunkSize = 4096; byte[] buffer = new byte[chu

  • C#利用Task实现任务超时多任务一起执行的方法

    前言 其实Task跟线程池ThreadPool的功能类似,不过写起来更为简单,直观.代码更简洁了,使用Task来进行操作.可以跟线程一样可以轻松的对执行的方法进行控制. 创建Task有两种方式,一种是使用构造函数创建,另一种是使用 Task.Factory.StartNew 进行创建. 如下代码所示 1.使用构造函数创建Task Task t1 = new Task(MyMethod); 2.使用Task.Factory.StartNew 进行创建Task Task t1 = Task.Fact

  • C# task应用实例详解

    Task的应用 ​Task的MSDN的描述如下: [Task类的表示单个操作不会返回一个值,通常以异步方式执行. Task对象是一种的中心思想基于任务的异步模式首次引入.NETFramework 4 中. 因为由执行工作Task对象通常以异步方式执行线程池线程上而不是以同步方式在主应用程序线程中,可以使用Status属性,并将IsCanceled, IsCompleted,和IsFaulted属性,以确定任务的状态. 大多数情况下,lambda 表达式用于指定该任务所执行的工作量. 对于返回值的

  • C#关于Task.Yeild()函数的讨论

    在与同事讨论async/await内部实现的时候,突然想到Task.Yeild()这个函数,为什么呢,了解一点C#async/await内部机制的都知道,在await一个异步任务(函数)的时候,它会先判断该Task是否已经完成,如果已经完成,则继续执行下去,不会返回到调用方,原因是尽量避免线程切换,因为await后面部分的代码很可能是另一个不同的线程执行,而Task.Yeild()则可以强制回到调用方,或者说主动让出执行权,给其他Task执行的机会,可以把Task理解为协程,Task.Yeild

  • c#文件的I/O基本操作

    文件是一些永久存储及具有特定顺序的字节组成的一个有序的,具有名称的集合.与文件有关的概念是目录路径和磁盘存储等.流提供了一种向后备存储写入字节和从后备存储读取字节的方式.后备存储包裹用文件存储或用内存(数组)存储,以及网络,CD等. 基本文件的I/O 命名空间为System.I/O,程序集为mscorlib(在mscorlib.dll中)抽象基类Stream支持读取和写入字节.Stream集成了异步支持,其默认实现根据其相应的异步方法来定义同步读取和写入.所有表示流的类都是从Stream类继承的

  • windows下C#定时管理器框架Task.MainForm详解

    入住博客园4年多了,一直都是看别人的博客,学习别人的知识,为各个默默无私贡献自己技术总结的朋友们顶一个:这几天突然觉得是时候加入该队列中,贡献出自己微弱的力量,努力做到每个月有不同学习总结,知识学习的分享文章.以下要分享的是花了两天时间编写+测试的windows下C#定时管理器框架-Task.MainForm. 目的: 随着这五年在几个公司做不同职位的.net研发者,发现各个公司都或多或少会对接一些第三方合作的接口或者数据抓取功能,都是那种各个服务直接没有关联性功能,开发人员也可能不是一个人,使

  • 详解C#中 Thread,Task,Async/Await,IAsyncResult的那些事儿

    说起异步,Thread,Task,async/await,IAsyncResult 这些东西肯定是绕不开的,今天就来依次聊聊他们 1.线程(Thread) 多线程的意义在于一个应用程序中,有多个执行部分可以同时执行:对于比较耗时的操作(例如io,数据库操作),或者等待响应(如WCF通信)的操作,可以单独开启后台线程来执行,这样主线程就不会阻塞,可以继续往下执行:等到后台线程执行完毕,再通知主线程,然后做出对应操作! 在C#中开启新线程比较简单 static void Main(string[]

  • C#中Task.Yield的用途深入讲解

    前言 最近在阅读 .NET Threadpool starvation, and how queuing makes it worse这篇博文时发现文中代码中的一种 Task 用法之前从未见过,在网上看了一些资料后也是云里雾里不知其解,很是困扰.今天在程序员节的大好日子里终于想通了,于是写下这篇随笔分享给大家,也过过专心写博客的瘾. 这种从未见过的用法就是下面代码中的 await Task.Yield() : static async Task Process() { await Task.Yi

  • c#异步task示例分享(异步操作)

    c# Task异步操作 复制代码 代码如下: using System;using System.Threading;using System.Threading.Tasks; namespace ConsoleApplication18{    class Program    {        static void Main(string[] args)        {            Func<string, string> _processTimeFunc = new Fun

随机推荐