[英]How to rewrite to Task<T> for performance gain?
我有以下代碼:
static BlockingCollection<SimpleObject> sendQueue = new BlockingCollection<SimpleObject>();
static public void Insert(string key, T value)
{
SimpleObject simpleObject = new SimpleObject {Key = key, Value = value};
sendQueue.Add(simpleObject);
var data = sendQueue.Take(); //this blocks if there are no items in the queue.
ThreadPool.QueueUserWorkItem(state =>
{
//Do ASYNC stuff with data here - threadsafe
});
}
我怎么寫這個來使用T的任務並仍然確保它的線程安全且快速? 還是有更好/更快的方式?
我認為你只需要2個線程/任務。 1名制片人和1名消費者。
//Producer
Task.Factory.StartNew(() =>
{
for(int i=0;i<100000000;i++)
{
sendQueue.Add(new SimpleObject() { Key = "", Value = "" });
}
sendQueue.CompleteAdding();
});
//Consumer
Task.Factory.StartNew(() =>
{
foreach(var so in sendQueue.GetConsumingEnumerable())
{
//do something
}
});
使用TPL重寫這一點會相對簡單
Task.Factory.StartNew(() => {
// do async stuff
});
但是,這並沒有使任何線程安全,這只是確保工作在一個單獨的線程上運行。 此外,它是否會更快是有爭議的,你需要對它進行基准測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.