Thread
cs
class Program
{
static void Main()
{
Thread thread = new Thread(new ThreadStart(DoWork));
thread.Start();
thread.Join(); // 等待线程完成
Console.WriteLine("主线程结束。");
}
static void DoWork()
{
Console.WriteLine("线程开始工作。");
Thread.Sleep(1000); // 模拟工作
Console.WriteLine("线程工作完成。");
}
}
ThreadPool
cs
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(DoWork);
ThreadPool.QueueUserWorkItem(state => DoWorkWithState((string)state), "参数");
// 防止主线程提前结束
Thread.Sleep(2000);
}
static void DoWork(object state)
{
Console.WriteLine("ThreadPool 工作项开始工作。");
Thread.Sleep(1000); // 模拟工作
Console.WriteLine("ThreadPool 工作项完成。");
}
static void DoWorkWithState(string state)
{
Console.WriteLine($"ThreadPool 带参数的工作项开始工作,参数:{state}");
Thread.Sleep(1000); // 模拟工作
Console.WriteLine($"ThreadPool 带参数的工作项完成。");
}
}
Task
cs
class Program
{
static async Task Main()
{
Task task = Task.Run(() => DoWork());
await task; // 等待任务完成
Console.WriteLine("主线程结束。");
}
static void DoWork()
{
Console.WriteLine("Task 开始工作。");
Task.Delay(1000).Wait(); // 模拟异步工作
Console.WriteLine("Task 工作完成。");
}
}
async/await
cs
class Program
{
static async Task Main()
{
string url = "https://www.example.com";
string content = await FetchContentAsync(url);
Console.WriteLine(content);
}
static async Task<string> FetchContentAsync(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
}