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;  
        }  
    }  
}
相关推荐
prinrf('千寻)21 分钟前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
m0_5557629031 分钟前
Qt缓动曲线详解
开发语言·qt
她说彩礼65万32 分钟前
C# lock
c#
揽你·入怀1 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
AA-代码批发V哥2 小时前
Math工具类全面指南
java·开发语言·数学建模
Nobkins2 小时前
2021ICPC四川省赛个人补题ABDHKLM
开发语言·数据结构·c++·算法·图论
十八年的好汉2 小时前
buck变换器的simulink/matlab仿真和python参数设计
开发语言·matlab
88号技师2 小时前
2025年6月一区SCI-不实野燕麦优化算法Animated Oat Optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
我不是程序猿儿2 小时前
【C#】Thread.Join()、异步等待和直接join
开发语言·c#
独行soc2 小时前
2025年渗透测试面试题总结-百度面经(题目+回答)
运维·开发语言·经验分享·学习·面试·渗透测试·php