我一直在試圖找到一個簡單的自定義線程池一段時間,並找不到一個,所以寫了一個快速窮人的線程池。C#。是否有自定義線程池的.NET類
問題:
有任何.NET類已經可以做到這一點? (無數次試圖找到它之後找不到它,只有博客文章中的自定義實現比這更復雜!)。
更好地消耗線程與輪詢或啓動線程池上的操作時和當任務進來? <每天1k任務。這將是對紅隼
運行的AspNetCore網站
代碼
public class WorkerQueue : IWorkerQueue
{
private readonly Queue<WorkItem> _items = new Queue<WorkItem>();
private int _max = 2; // Would be configurable
private int _running;
private Stopwatch _stopwatch;
public WorkerQueue()
{
_stopwatch = new Stopwatch();
_stopwatch.Start();
}
public void Add(WorkItem workItem)
{
lock (_items)
{
if (_running >= _max)
{
Log($"Queuing Item {workItem.Name} - _running >= _max");
_items.Enqueue(workItem);
return;
}
_running++;
Log($"Running Item {workItem.Name} - _running = {_running}");
var task = Task.Run(workItem.Action);
task.ContinueWith(t => OnActionCompleted(workItem.Name));
}
}
private void Log(string msg)
{
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} @ {_stopwatch.ElapsedMilliseconds}ms : {msg}");
}
private void OnActionCompleted(string obj)
{
Log($"OnActionCompleted {obj}");
WorkItem item = null;
lock (_items)
{
if (_items.Count > 0)
item = _items.Dequeue();
else
_running--;
}
if (item != null)
{
// Potential Stack Overflow if big queue builds up?
// Probably should be a while loop rather than recursion?
Log($"Running Next Item {item.Name}");
item.Action();
OnActionCompleted(item.Name);
}
else
{
Log($"Sleeping. _running = {_running}");
}
}
}
和測試:
[Fact]
public void Test()
{
var sb = new StringBuilder();
Console.SetOut(new StringWriter(sb));
var resetEvent = new ManualResetEventSlim();
AddItem("A", 100);
AddItem("B", 250);
AddItem("C", 100);
AddItem("D", 100);
AddItem("E", 100);
AddItem("G", 100,() =>
{
Thread.Sleep(250);
resetEvent.Set();
});
resetEvent.Wait(2500);
Assert.True(resetEvent.IsSet);
_output.WriteLine("");
_output.WriteLine("------------------ Test Finished ------------------");
_output.WriteLine("------------------ Console Out ------------------");
_output.WriteLine("");
_output.WriteLine(sb.ToString());
}
而得到這個輸出是正確的(或相當正確的)
Thread 14 @ 8ms : Running Item A - _running = 1
Thread 14 @ 8ms : Running Item B - _running = 2
Thread 14 @ 8ms : Queuing Item C - _running >= _max
Thread 14 @ 8ms : Queuing Item D - _running >= _max
Thread 14 @ 8ms : Queuing Item E - _running >= _max
Thread 14 @ 8ms : Queuing Item G - _running >= _max
Thread 21 @ 110ms : OnActionCompleted A
Thread 21 @ 110ms : Running Next Item C
Thread 21 @ 211ms : OnActionCompleted C
Thread 21 @ 211ms : Running Next Item D
Thread 20 @ 260ms : OnActionCompleted B
Thread 20 @ 260ms : Running Next Item E
Thread 21 @ 311ms : OnActionCompleted D
Thread 21 @ 311ms : Running Next Item G
Thread 20 @ 360ms : OnActionCompleted E
Thread 20 @ 360ms : Sleeping. _running = 1
Thread 21 @ 662ms : OnActionCompleted G
Thread 21 @ 662ms : Sleeping. _running = 0
我投票結束這個問題作爲題外話,因爲它應該屬於http://codereview.stackexchange.com網站 –
@SergeyBerezovskiy改變了問題,問是否已經有一些可用的.NET框架已經存在 –
任務是.NETCore中的新線程,它通過線程池進行管理。 –