Ryhan
Ryhan

Reputation: 1885

C# Threading Wonders

Lets say you would like to add items to a data structure in C# asynchronously.

So the typical step by step procedure would usually follow:

List1.add(variable1); 

List2.add(variable2);

List3.add(variable3);

..etc.

Is it possible to do this asynchronously?

I will say also say there are no dependencies between each list or it's respective variable.

Can this be done nicely?

Upvotes: 1

Views: 120

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273244

I will say also say there are no dependencies between each list or it's respective variable.
Can this be done nicely?

Yes, as long as each thread has its own list there is no problem a all.

And a simple way to do it:

Parallel.Invoke(
   () => List1.add(variable1), 
   () => List2.add(variable2),
   () => List3.add(variable3)
);

On the other hand, List<>.Add() is a pretty small and fast method so you won't see much benefit of doing this. There's only a gain when 2+ lists need to grow internally at the same time. And there are better ways to deal with that.

Upvotes: 5

Related Questions