asp.net core C#设计一个实用的线程池
时间: 2024-05-16 14:16:45 浏览: 11
在ASP.NET Core C#中,可以使用System.Threading.Tasks.Task类来创建和管理线程池。以下是一个简单的线程池实现:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadPoolDemo
{
public class MyThreadPool
{
private readonly Queue<Action> _tasks = new Queue<Action>();
private readonly object _lock = new object();
private readonly int _maxThreads;
private int _runningThreads = 0;
private bool _disposed = false;
public MyThreadPool(int maxThreads)
{
_maxThreads = maxThreads;
}
public void QueueTask(Action task)
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(MyThreadPool));
}
lock (_lock)
{
_tasks.Enqueue(task);
if (_runningThreads < _maxThreads)
{
Interlocked.Increment(ref _runningThreads);
Task.Factory.StartNew(ExecuteTask, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
}
private void ExecuteTask()
{
while (true)
{
Action task = null;
lock (_lock)
{
if (_tasks.Count > 0)
{
task = _tasks.Dequeue();
}
else
{
Interlocked.Decrement(ref _runningThreads);
break;
}
}
task();
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
lock (_lock)
{
while (_tasks.Count > 0)
{
var task = _tasks.Dequeue();
}
_runningThreads = 0;
}
}
}
}
```
使用示例:
```csharp
using System;
namespace ThreadPoolDemo
{
class Program
{
static void Main(string[] args)
{
using (var pool = new MyThreadPool(4))
{
for (int i = 0; i < 10; i++)
{
var index = i;
pool.QueueTask(() => Console.WriteLine($"Task {index} is running on thread {Thread.CurrentThread.ManagedThreadId}"));
}
}
}
}
}
```
这个线程池实现使用一个队列来存储待执行的任务。当有新的任务加入队列时,它会检查当前运行的线程数量是否已经达到最大值,如果没有,则创建新的线程来执行任务。当所有任务执行完毕时,线程池会自动关闭所有线程。
请注意,这个线程池实现只是一个简单的示例,没有考虑到一些高级功能,例如线程异常处理、任务取消等。在实际应用中,需要根据实际需求进行完善。