在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.");
});
// 等待任務(wù)完成
task.Wait();
}
}
async
和await
關(guān)鍵字處理異步方法: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.");
});
// 等待所有任務(wù)完成
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;
})
};
// 等待所有任務(wù)完成并獲取結(jié)果
int[] results = await Task.WhenAll(tasks);
Console.WriteLine($"The results are: {string.Join(", ", results)}");
}
}
這些示例展示了如何使用C# Task
類處理并發(fā)任務(wù)。請(qǐng)注意,為了確保代碼的可讀性和可維護(hù)性,建議使用async
和await
關(guān)鍵字來處理異步操作。