我使用以下代码创建两个线程并等待它们完成:
Task task1 = Task.Factory.StartNew(() => DoSomething(a, b));
Task task2 = Task.Factory.StartNew(() => DoSomething(a, b));
Task.WaitAll(task1, task2);
DoSomething方法返回的返回类型为字符串,当两个任务完成时,我想使用它的返回值。
我尝试创建两个字符串变量,并为它们分配返回值,如:
string x, y;
Task task1 = Task.Factory.StartNew(() => x = DoSomething(a, b));
Task task2 = Task.Factory.StartNew(() => y = DoSomething(a, b));
但是我收到编译时错误,x和y未分配,我在这里缺少什么?
答案 0 :(得分:2)
尝试使用Task<string>
代替Task
并查询Task<string>.Result
答案 1 :(得分:0)
使用Task.Run
var task1 = Task.Run(() => DoSomething(a, b));
var task2 = Task.Run(() => DoSomething(a, b));
var result1 = await task1;
var result2 = await task2;
答案 2 :(得分:0)
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));
此后
Task.WhenAll(task1, task2).ContinueWith((tasks)=>{ // access results here});