当前位置: 首页>>代码示例>>C#>>正文


C# Task类代码示例

本文整理汇总了C#中System.Threading.Tasks.Task的典型用法代码示例。如果您正苦于以下问题:C# Task类的具体用法?C# Task怎么用?C# Task使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Task类属于System.Threading.Tasks命名空间,在下文中一共展示了Task类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

class Example
{
    static void Main()
    {
        Action<object> action = (object obj) =>
                                {
                                   Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                   Task.CurrentId, obj,
                                   Thread.CurrentThread.ManagedThreadId);
                                };

        // Create a task but do not start it.
        Task t1 = new Task(action, "alpha");

        // Construct a started task
        Task t2 = Task.Factory.StartNew(action, "beta");
        // Block the main thread to demonstrate that t2 is executing
        t2.Wait();

        // Launch t1 
        t1.Start();
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId);
        // Wait for the task to finish.
        t1.Wait();

        // Construct a started task using Task.Run.
        String taskData = "delta";
        Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                     Task.CurrentId, taskData,
                                                      Thread.CurrentThread.ManagedThreadId);
                                   });
        // Wait for the task to finish.
        t3.Wait();

        // Construct an unstarted task
        Task t4 = new Task(action, "gamma");
        // Run it synchronously
        t4.RunSynchronously();
        // Although the task was run synchronously, it is a good practice
        // to wait for it in the event exceptions were thrown by the task.
        t4.Wait();
    }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:49,代码来源:Task

输出:

Task=1, obj=beta, Thread=3
t1 has been launched. (Main Thread=1)
Task=2, obj=alpha, Thread=4
Task=3, obj=delta, Thread=3
Task=4, obj=gamma, Thread=1

示例2: Main

//引入命名空间
using System;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      await Task.Run( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:18,代码来源:Task

输出:

Finished 1000001 loop iterations

示例3: Main

//引入命名空间
using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:19,代码来源:Task

输出:

Finished 1000001 loop iterations

示例4: Random

//引入命名空间
using System;   
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Wait on a single task with no timeout specified.
        Task taskA = Task.Run( () => Thread.Sleep(2000));
        Console.WriteLine("taskA Status: {0}", taskA.Status);
        try {
          taskA.Wait();
          Console.WriteLine("taskA Status: {0}", taskA.Status);
       } 
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
    }    
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:23,代码来源:Task

输出:

taskA Status: WaitingToRun
taskA Status: RanToCompletion

示例5: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait on a single task with a timeout specified.
      Task taskA = Task.Run( () => Thread.Sleep(2000));
      try {
        taskA.Wait(1000);       // Wait for 1 second.
        bool completed = taskA.IsCompleted;
        Console.WriteLine("Task A completed: {0}, Status: {1}",
                         completed, taskA.Status);
        if (! completed)
           Console.WriteLine("Timed out before task A completed.");                 
       }
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:24,代码来源:Task

输出:

Task A completed: False, Status: Running
Timed out before task A completed.

示例6: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new Task[3];
      var rnd = new Random();
      for (int ctr = 0; ctr <= 2; ctr++)
         tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

      try {
         int index = Task.WaitAny(tasks);
         Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
         Console.WriteLine("Status of all tasks:");
         foreach (var t in tasks)
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
      }
      catch (AggregateException) {
         Console.WriteLine("An exception occurred.");
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:26,代码来源:Task

输出:

Task #1 completed first.

Status of all tasks:
Task #3: Running
Task #1: RanToCompletion
Task #4: Running

示例7: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait for all tasks to complete.
      Task[] tasks = new Task[10];
      for (int i = 0; i < 10; i++)
      {
          tasks[i] = Task.Run(() => Thread.Sleep(2000));
      }
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
         Console.WriteLine("One or more exceptions occurred: ");
         foreach (var ex in ae.Flatten().InnerExceptions)
            Console.WriteLine("   {0}", ex.Message);
      }   

      Console.WriteLine("Status of completed tasks:");
      foreach (var t in tasks)
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:29,代码来源:Task

输出:

Status of completed tasks:
Task #2: RanToCompletion
Task #1: RanToCompletion
Task #3: RanToCompletion
Task #4: RanToCompletion
Task #6: RanToCompletion
Task #5: RanToCompletion
Task #7: RanToCompletion
Task #8: RanToCompletion
Task #9: RanToCompletion
Task #10: RanToCompletion

示例8: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Create a cancellation token and cancel it.
      var source1 = new CancellationTokenSource();
      var token1 = source1.Token;
      source1.Cancel();
      // Create a cancellation token for later cancellation.
      var source2 = new CancellationTokenSource();
      var token2 = source2.Token;
       
      // Create a series of tasks that will complete, be cancelled, 
      // timeout, or throw an exception.
      Task[] tasks = new Task[12];
      for (int i = 0; i < 12; i++)
      {
          switch (i % 4) 
          {
             // Task should run to completion.
             case 0:
                tasks[i] = Task.Run(() => Thread.Sleep(2000));
                break;
             // Task should be set to canceled state.
             case 1:   
                tasks[i] = Task.Run( () => Thread.Sleep(2000),
                         token1);
                break;         
             case 2:
                // Task should throw an exception.
                tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );
                break;
             case 3:
                // Task should examine cancellation token.
                tasks[i] = Task.Run( () => { Thread.Sleep(2000); 
                                             if (token2.IsCancellationRequested)
                                                token2.ThrowIfCancellationRequested();
                                             Thread.Sleep(500); }, token2);   
                break;
          }
      }
      Thread.Sleep(250);
      source2.Cancel();
       
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
          Console.WriteLine("One or more exceptions occurred:");
          foreach (var ex in ae.InnerExceptions)
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message);
       }   

      Console.WriteLine("\nStatus of tasks:");
      foreach (var t in tasks) {
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
         if (t.Exception != null) {
            foreach (var ex in t.Exception.InnerExceptions)
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message);
         }
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:69,代码来源:Task

输出:

One or more exceptions occurred:
TaskCanceledException: A task was canceled.
NotSupportedException: Specified method is not supported.
TaskCanceledException: A task was canceled.
TaskCanceledException: A task was canceled.
NotSupportedException: Specified method is not supported.
TaskCanceledException: A task was canceled.
TaskCanceledException: A task was canceled.
NotSupportedException: Specified method is not supported.
TaskCanceledException: A task was canceled.

Status of tasks:
Task #13: RanToCompletion
Task #1: Canceled
Task #3: Faulted
NotSupportedException: Specified method is not supported.
Task #8: Canceled
Task #14: RanToCompletion
Task #4: Canceled
Task #6: Faulted
NotSupportedException: Specified method is not supported.
Task #7: Canceled
Task #15: RanToCompletion
Task #9: Canceled
Task #11: Faulted
NotSupportedException: Specified method is not supported.
Task #12: Canceled


注:本文中的System.Threading.Tasks.Task类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。