在C#中,Task
类是用于表示异步操作的一种方式
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();
}
}
async
和await
关键字处理异步方法: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.");
});
}
}
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);
}
}
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}");
}
}
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
类处理并发任务。请注意,为了确保代码的可读性和可维护性,建议使用async
和await
关键字来处理异步操作。