Currently I was working on parallel threads in C#. So, I have confusion of using ConcurrentBag<T>
and List<T>
.
Here is my code:
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;
}
For var b = new List ();
Is it mandatory of ConcurrentBag<T>
in multi-threading or can I use List<T>
which is best way of writing the code with respective of performance.
which one is better Concurrentbag<T>
or List<T>
in the above part of code?
Thanks in Advance!
CodePudding user response:
Because your inner list is never used concurrently you also do not need to use a ConcurrentBag<T>
here.
Commented your example a bit. From what I expect your code is doing I would take ICollection<T>
or IEnumerable<T>
in the 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;
}