目前我正在研究 C# 中的并行執行緒。所以,我對使用ConcurrentBag<T>and感到困惑List<T>。
這是我的代碼:
public async Task<ConcurrentDictionary<string, ConcurrentBag<T>>> MethodA(SearchResults<Result> response)
{
var a = new ConcurrentDictionary<string, ConcurrentBag<DeviceAlertAlarm>>();
var tasks = response.GetResults().Select(async result) =>
{
var b = new List <T>();
// do something
a["xxx"] = b;
});
await Task.WhenAll(tasks);
return a;
}
對于var b = new List ();
ConcurrentBag<T>在多執行緒中是強制性的還是我可以使用List<T>哪種是撰寫具有各自性能的代碼的最佳方式。
哪個更好Concurrentbag<T>或List<T> 在代碼的上述部分?
提前致謝!
uj5u.com熱心網友回復:
因為您的內部串列永遠不會同時使用,所以您也不需要在ConcurrentBag<T>此處使用 a 。
稍微評論了你的例子。從我期望你的代碼正在做的事情來看,我會采取ICollection<T>或IEnumerable<T>在ConcurrentDictionary<string, IEnumerable<T>>.
// IEnumerable, List, Collection ... is enough here.
public async Task<ConcurrentDictionary<string, IEnumerable<T>>> MethodA(SearchResults<Result> response)
{
var a = new ConcurrentDictionary<string, IEnumerable<DeviceAlertAlarm>>();
var tasks = response.GetResults().Select(async (result) =>
{
//
// This list just exists and is accessed in this 'task/thread/delegate'
var b = new List<T>();
//
// do something ...
//
// The surrounding IDictionary as you have it here
// is used *concurrently* so this is enough to be thread-safe
a["xxx"] = b;
});
await Task.WhenAll(tasks);
return a;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521476.html
