温馨提示×

c# threadstart怎样与ThreadPool配合

c#
小樊
82
2024-06-24 10:13:25
栏目: 编程语言

在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方法来启动一个新线程。这样可以有效地利用线程池中的线程资源,避免频繁地创建和销毁线程。

0