[英]ThreadPool with controlled task affinity in C#
嗨,我想有一個線程池類,它確保某些任務將在同一線程中執行。 看到這個簡單的API:
class ThreadPoolWithAffinity{
// All tasks with the same key should be queued to the same thread
void EnqueueTask(Task t, Key k);
}
是否有一些已經發明了“輪子”的圖書館?
假設您有多個Web客戶端使用者,正在等待事件,並且假設發送事件是相對較長的操作,您更喜歡通過創建發送ceratin事件並將其放置到TP的任務來並行執行。 要保留事件的順序,您需要將創建用於將事件發送到特定客戶端的所有任務都由同一線程處理
一點也不。 您僅需要在所有依賴項都完成后才開始任務。 無需使用相同的線程。
假設您要發出具有以下依賴關系的請求A,B,C和D:
A and B independent
B after A
C after A and B
然后你寫:
Task a = RequestAsync("A");
Task b = RequestAsync("B");
Task c = a.ContinueWith(_ => RequestAsync("C")).Unwrap();
Task d = Task.WhenAll(a, b).ContinueWith(_ => RequestAsync("D")).Unwrap();
現在已設置所有依賴項。 您還可以動態添加工作。
您可以通過這種方式構建任意DAG。
聽起來TPL是您想要的,尤其是Task.ContinueWith
。 例:
var task1 = Task.Factory.StartNew(() =>
{
DoSomeLongComputation();
});
// This task will start as soon as the first is finished
task1.ContinueWith(task =>
{
DoAnotherLongComputation();
});
如果您構建將任務分配給鍵的Dictionary<Key, Task>
,則可以使用ContinueWith()
新任務入隊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.