Task多线程模型

一:同步编程模型(SPM)

单线线程、串行开发模式。

二:异步编程模型(APM)

xxxbegin、xxxend的模式。

   FileStream file = new FileStream(Environment.CurrentDirectory+"//1.txt",FileMode.Open);
var bytes= new byte[file.Length];

   file.BeginRead(bytes,0,bytes.Length,(ary)=> {
       var nums = file.EndRead(ary);
       Console.WriteLine(nums);
   },string.Empty);

   Console.Read();

三:基于事件的编程模型(EAP)

xxAsync这样的事件模式。 eg:WebClient。

四:基于Task的编程模型(TAP)

APM和EAP都可以使用Task来实现,微软的初衷就是想通过Task大一统异步编程领域

使用Task封装APM模式:

代码量小

Task更简单

FileStream file = new FileStream(Environment.CurrentDirectory+"//1.txt",FileMode.Open);

       var bytes= new byte[file.Length];
        var task = Task.Factory.FromAsync(file.BeginRead, file.EndRead, bytes, 0, bytes.Length, string.Empty);

        var nums = task.Result;
        Console.WriteLine(nums);

使用Task包装EAP

TaskCompletionSource:包装器

  private static Task<int> GetTask(string url)
     {
         TaskCompletionSource<int> source = new TaskCompletionSource<int>();
WebClient client = new WebClient();
     client.DownloadDataCompleted += (sendr, e) =>
     {
         try
         {
             source.TrySetResult(e.Result.Length);
         }
         catch (Exception ex)
         {
             source.TrySetException(ex);
         }

     };
     client.DownloadDataAsync(new Uri(url));
     return source.Task;
 }