Task C#后台任务
C# 创建一个没有返回值的任务
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建并启动一个没有返回值的任务
Task task1 = Task.Run(() =>
{
Console.WriteLine("Task 1 is running on a thread pool thread.");
Thread.Sleep(2000); // Simulate work with Sleep
Console.WriteLine("Task 1 has completed.");
});
// 创建并启动一个有返回值的任务
Task<int> task2 = Task.Run(() =>
{
Console.WriteLine("Task 2 is performing some calculations...");
Thread.Sleep(1500); // Simulate work with Sleep
return 42; // Return the result of the calculation
});
// Wait for both tasks to complete and handle their results.
System.Console.WriteLine("Main thread is waiting for Task 1 to complete.");
await Task.WhenAll(task1, task2);
// Get the result from task2.
int result = await task2;
Console.WriteLine($"The result from Task 2 is: {result}");
}
}
C# 创建一个可以取消的任务
class Program
{
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
try
{
Task task3 = Task.Run(
() =>
{
while (true)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested, task 3 is stopping.");
break;
}
Console.WriteLine("Task 3 is working...");
Thread.Sleep(500);
}
},
cts.Token
);
// Let task3 run for a short time before cancelling it.
await Task.Delay(2000);
// 只要cts.Cancel()就会一直运行,
标签:Task,Console,cts,C#,result,WriteLine,后台任务
From: https://www.cnblogs.com/zhuoss/p/18686835