.net core 如何使用线程池
时间: 2023-06-29 12:10:16 浏览: 65
在 .NET Core 中,我们可以使用 System.Threading.ThreadPool 类来使用线程池。以下是使用线程池的示例代码:
```csharp
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
// Queue a task to the thread pool.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
// If we comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
// This thread procedure performs the task.
static void ThreadProc(Object stateInfo)
{
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}
```
在上面的示例中,我们使用 `ThreadPool.QueueUserWorkItem` 方法将一个任务放入线程池中,并传递了一个委托方法 `ThreadProc` 作为任务的执行体。
当运行这段代码时,我们会看到输出结果为:
```
Main thread does some work, then sleeps.
Hello from the thread pool.
Main thread exits.
```
注意:在使用线程池时,我们需要确保任务的执行体是线程安全的,以避免潜在的竞态条件问题。