.net core 线程池帮助类
时间: 2023-06-28 19:12:31 浏览: 48
可以使用 .NET Core 中提供的 ThreadPool 类来操作线程池,同时也可以使用 Task.Run() 方法来将任务提交给线程池执行。下面是一个示例代码:
```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args)
{
// 设置最大线程数
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMaxThreads(4, completionPortThreads);
// 提交任务给线程池执行
for (int i = 0; i < 10; i++)
{
Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} started on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(1000);
Console.WriteLine($"Task {Task.CurrentId} completed on thread {Thread.CurrentThread.ManagedThreadId}");
});
}
Console.ReadLine();
}
}
```
在上述代码中,我们首先设置了线程池的最大线程数为 4,然后使用 Task.Run() 方法提交了 10 个任务给线程池执行。每个任务都会打印出当前任务的 ID 和所在的线程 ID。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)