简体   繁体   English

C#.Net等待所有线程完成并获取返回值

[英]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. DoSomething方法返回的返回类型为字符串,当两个任务都完成时,我想使用它的返回值。

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? 但是我收到一个未分配x和y的编译时错误,我在这里错过了什么?

尝试使用Task<string>代替Task并查询Task<string>.Result

It is easy to accomplish using Task.Run 使用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 在第一行中,将x和y的默认值分配为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});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM