C#多线程的4中方式

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;  
        }  
    }  
}
相关推荐
皮卡蛋炒饭.43 分钟前
线程的概念和控制
java·开发语言·jvm
John.Lewis44 分钟前
Python小课(1)认识Python
开发语言·python
一只大袋鼠1 小时前
MyBatis 入门详细实战教程(一):从环境搭建到查询运行
java·开发语言·数据库·mysql·mybatis
sonnet-10291 小时前
函数式接口和方法引用
java·开发语言·笔记
Bat U1 小时前
JavaEE|多线程(二)
java·开发语言
烤麻辣烫2 小时前
JS基础
开发语言·前端·javascript·学习
froginwe112 小时前
C++ 文件和流
开发语言
hez20102 小时前
C# 15 类型系统改进:Union Types
c#·.net·.net core
Dxy12393102162 小时前
Python在图片上画矩形:从简单边框到复杂标注的全攻略
开发语言·python
独自破碎E2 小时前
面试官:你有用过Java的流式吗?比如说一个列表.stream这种,然后以流式去处理数据。
java·开发语言