c# threadstart怎样与ThreadPool配合

   2024-10-08 9790
核心提示:在C#中,可以使用ThreadPool.QueueUserWorkItem方法来将一个方法放入线程池中执行。可以在ThreadStart委托中指定要执行的方法,

在C#中,可以使用ThreadPool.QueueUserWorkItem方法来将一个方法放入线程池中执行。可以在ThreadStart委托中指定要执行的方法,然后再使用ThreadPool.QueueUserWorkItem方法将该委托放入线程池中执行。

示例代码如下:

using System;using System.Threading;class Program{    static void Main()    {        ThreadStart start = new ThreadStart(MyMethod);        // 将委托放入线程池中执行        ThreadPool.QueueUserWorkItem(new WaitCallback(start));        Console.WriteLine("Main thread is running...");        Console.ReadLine();    }    static void MyMethod()    {        Console.WriteLine("MyMethod is running on a separate thread...");    }}

在上面的示例中,我们通过ThreadPool.QueueUserWorkItem方法将MyMethod方法放入线程池中执行,而不是直接使用Thread.Start方法来启动一个新线程。这样可以有效地利用线程池中的线程资源,避免频繁地创建和销毁线程。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号