在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#中創建和管理任務。你可以根據需要調整代碼以適應不同的場景。