タスク使用履歴


C〓〓4.0があって、4.0以下のは試しません.
 

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.  
  6. using System.Threading.Tasks;  
  7. using System.Threading;  
  8.  
  9. namespace TaskDemo  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             try 
  16.             {  
  17.                 int mCount = 0;  
  18.  
  19.                 CancellationTokenSource tokenSource = new CancellationTokenSource();  
  20.                 CancellationToken token = tokenSource.Token;  
  21.  
  22.                 Task t = new Task(() =>  
  23.                 {  
  24.                     Thread.Sleep(1000);  
  25.                     Console.WriteLine(" ……");  
  26.                     //      
  27.                     for (int i = 0; i < 3000; i++)  
  28.                     {  
  29.                         if (token.IsCancellationRequested == true)  
  30.                         {  
  31.                             break;          // throw new OperationCanceledException(token);   
  32.                         }  
  33.                         mCount++;  
  34.                         Thread.Sleep(1);   
  35.                     }  
  36.                 }, token);  
  37.                 token.Register(() =>  
  38.                {      
  39.  
  40.                    Console.WriteLine("Canceled");  
  41.  
  42.                });  
  43.                 t.Start();  
  44.                 Console.WriteLine(" ……");  
  45.                 t.ContinueWith((task) =>  
  46.                 {  
  47.                     Console.WriteLine(" , :");  
  48.                     Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}\tmCount={3}", task.IsCanceled, task.IsCompleted, task.IsFaulted, mCount);  
  49.                 });  
  50.                 Console.WriteLine(" , ……");  
  51.                 Console.ReadKey();      // sleep , ,  
  52.                 tokenSource.Cancel();  
  53.                 Console.ReadKey();      //  
  54.  
  55.             }  
  56.             catch (Exception Ex)  
  57.             {  
  58.                 Console.WriteLine(Ex.Message);  
  59.             }  
  60.  
  61.         }  
  62.     }  
  63. }  
  64.  
  65.  
  66.  
  67.