Reputation: 3357
I have few task which I can do in parallel. As list is not thread safe i am using concurrentbag
. Once all the task are completed I want to convert the concurrentbag
to list.
I have searched in MSDN but couldn't find any API which can convert concurrentbag to list in c#. How can I do it?
Note: i have to convert to list, It is necessary.
I have other option to apply lock on list but i wanted to use in build concurrentbag
which is thread safe.
Upvotes: 12
Views: 22676
Reputation: 1394
If your internal item are non list then use
var someList = someConcurrentBag.ToList();
Or you can try as below If each item in the cbag is already a list.
E.g. In my case ConcurrentBag<List<int>>
ConcurrentBag<List<string>> jobErrorsColl = new ConcurrentBag<List<string>>();
// Got something in jobErrorsColl
List<string> multipleJobErrors = new List<string>();
List<string> singleJobErrors = new List<string>();
while (jobErrorsColl.IsEmpty)
{
jobErrorsColl.TryPeek(out singleJobErrors);
multipleJobErrors.AddRange(singleJobErrors);
}
return multipleJobErrors;
MSDN link is here for the same
Upvotes: 2
Reputation: 11
You can use the following to convert concurrentbag to list:
var list = = someConcurrentBag.SelectMany(r => r).ToList();
Upvotes: 0
Reputation: 37299
ConcurrentBag
has the extension method of .ToList()
- it implementsIEnumerable<T>
var someList = someConcurrentBag.ToList();
Upvotes: 7
Reputation: 16956
You could use ToList
extension method.
var list = concurrentBag.ToList();
Upvotes: 20