在C#中,Task
是一种轻量级的线程,用于执行异步操作
Task.Run
创建并启动一个新任务:using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await Task.Run(() =>
{
Console.WriteLine("Hello from task!");
});
}
}
Task.Factory.StartNew
创建并启动一个新任务:using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var task = Task.Factory.StartNew(() =>
{
Console.WriteLine("Hello from task!");
});
await task;
}
}
TaskCompletionSource<T>
创建一个可以手动控制完成状态的任务:using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var tcs = new TaskCompletionSource<bool>();
// Simulate an asynchronous operation
Task.Run(() =>
{
Console.WriteLine("Hello from task!");
tcs.SetResult(true);
});
await tcs.Task;
}
}
Task.WhenAll
等待多个任务完成:using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var task1 = Task.Run(() =>
{
Console.WriteLine("Task 1");
});
var task2 = Task.Run(() =>
{
Console.WriteLine("Task 2");
});
await Task.WhenAll(task1, task2);
}
}
Task.WhenAny
等待多个任务中的一个完成:using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var task1 = Task.Delay(1000).ContinueWith(_ => "Task 1");
var task2 = Task.Delay(2000).ContinueWith(_ => "Task 2");
var completedTask = await Task.WhenAny(task1, task2);
Console.WriteLine($"Completed task: {completedTask.Result}");
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var cts = new CancellationTokenSource();
var task = Task.Run(() =>
{
while (!cts.Token.IsCancellationRequested)
{
Console.WriteLine("Task is running...");
Thread.Sleep(500);
}
}, cts.Token);
// Cancel the task after 2 seconds
await Task.Delay(2000);
cts.Cancel();
try
{
await task;
}
catch (OperationCanceledException)
{
Console.WriteLine("Task was canceled.");
}
}
}
这些示例展示了如何在C#中创建和管理任务。你可以根据需要调整代码以适应不同的场景。