如何使用C# Task处理并发任务

avatar
作者
猴君
阅读量:0

在C#中,Task类是用于表示异步操作的一种方式

  1. 创建并启动一个简单的任务:
using System; using System.Threading.Tasks;  class Program {     static void Main(string[] args)     {         Task task = Task.Run(() =>         {             Console.WriteLine("Running a task on a separate thread.");         });          // 等待任务完成         task.Wait();     } } 
  1. 使用asyncawait关键字处理异步方法:
using System; using System.Threading.Tasks;  class Program {     static async Task Main(string[] args)     {         await RunAsyncTask();     }      static async Task RunAsyncTask()     {         await Task.Run(() =>         {             Console.WriteLine("Running an asynchronous task on a separate thread.");         });     } } 
  1. 处理多个并发任务:
using System; using System.Threading.Tasks;  class Program {     static async Task Main(string[] args)     {         Task task1 = Task.Run(() =>         {             Console.WriteLine("Running task 1 on a separate thread.");         });          Task task2 = Task.Run(() =>         {             Console.WriteLine("Running task 2 on a separate thread.");         });          // 等待所有任务完成         await Task.WhenAll(task1, task2);     } } 
  1. 处理任务返回值:
using System; using System.Threading.Tasks;  class Program {     static async Task Main(string[] args)     {         Task<int> task = Task.Run(() =>         {             Console.WriteLine("Running a task with return value on a separate thread.");             return 42;         });          int result = await task;         Console.WriteLine($"The result is: {result}");     } } 
  1. 处理多个并发任务并获取结果:
using System; using System.Linq; using System.Threading.Tasks;  class Program {     static async Task Main(string[] args)     {         Task<int>[] tasks = new[]         {             Task.Run(() =>             {                 Console.WriteLine("Running task 1 on a separate thread.");                 return 1;             }),             Task.Run(() =>             {                 Console.WriteLine("Running task 2 on a separate thread.");                 return 2;             })         };          // 等待所有任务完成并获取结果         int[] results = await Task.WhenAll(tasks);         Console.WriteLine($"The results are: {string.Join(", ", results)}");     } } 

这些示例展示了如何使用C# Task类处理并发任务。请注意,为了确保代码的可读性和可维护性,建议使用asyncawait关键字来处理异步操作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!