深く分析する

29021 ワード

TaskのMSDNの記述は以下の通りである。
【Taskクラスの表現は、単一の動作は1つの値に戻りません。通常は非同期的に実行されます。
Taskオブジェクトはタスクの非同期モードに基づいて初めて導入された中心思想である。
作業Taskオブジェクトによって、通常は非同期的にスレッドスレッドスレッド上を実行するので、メインアプリケーションスレッドではなくSttus属性を使用して、Is Cancelled、Is Comppleted、Is Faulted属性をタスクの状態を決定します。
多くの場合、このタスクが実行される作業量を指定するためにlamda表現が使用されます。
戻り値の操作には、Taskクラスを使います。
1、Taskの強み
ThreadPoolはThreadに比べて多くの利点を備えていますが、ThreadPoolはまたいくつかの使用上の不便があります。たとえば:
  • ThreadPoolはスレッドのキャンセル、完了、失敗通知などのインタラクティブ操作をサポートしていません。
  • ThreadPoolはスレッド実行の順序をサポートしていません。
  • 以前、開発者が上記の機能を実現するには、多くの追加的な作業を完了する必要がありました。現在、FCLではより強力な機能を提供しています。Task。Taskオンラインプログラムをベースに最適化し、より多くのAPIを提供しています。FCC 4.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
    簡単デモ:
    
    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.AttachedToPartent)の親のタスクは、すべてのサブタスクが完了するまで待機しています。
    
    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.From Resoultのアプリケーション
    
    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のみを提供し、Report方法により一つのTタイプの値をIProgressに報告し、その後IProgress<in T>の実現クラスProggress<in T>のコンストラクタ受信タイプはAct<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.From Ayncのアプリケーション(シンプル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に関しての資料は私達のその他の関連している文章に関心を持って下さい!