Gurvinder Singh
Gurvinder Singh

Reputation: 111

C# .Net Wait for all threads to complete and get return values

I am using the following code to create two threads and wait them to complete:

Task task1 = Task.Factory.StartNew(() => DoSomething(a, b));
Task task2 = Task.Factory.StartNew(() => DoSomething(a, b));

Task.WaitAll(task1, task2);

The DoSomething Method returns has a return type of string and when both of the tasks finish I want to use the return value of it.

I tried creating two string variables, and assign them value returned like:

string x, y;
Task task1 = Task.Factory.StartNew(() => x = DoSomething(a, b));
Task task2 = Task.Factory.StartNew(() => y = DoSomething(a, b));

But I get a compile time error that x and y are unassigned, what am I missing here?

Upvotes: 1

Views: 1356

Answers (3)

Tomas Chabada
Tomas Chabada

Reputation: 3019

It is easy to accomplish using Task.Run

var task1 = Task.Run(() => DoSomething(a, b));
var task2 = Task.Run(() => DoSomething(a, b));
var result1 = await task1;
var result2 = await task2;

Upvotes: 0

Vignesh.N
Vignesh.N

Reputation: 2666

he says its a compile time error; I am assuming it is blaming for default values. in your first line, assign the default value for x and y to null

string x = null;
string y = null;
Task task1 = Task.Factory.StartNew(() => x = DoSomething(a, b));
Task task2 = Task.Factory.StartNew(() => y = DoSomething(a, b));

also after this

Task.WhenAll(task1, task2).ContinueWith((tasks)=>{ // access results here});

Upvotes: 0

Iain Brown
Iain Brown

Reputation: 1171

Try using a Task<string> instead of a Task and querying the Task<string>.Result

Upvotes: 2

Related Questions