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?
尝试使用Task<string>
代替Task
并查询Task<string>.Result
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;
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});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.