简体   繁体   English

如何从Task.Factory.StartNew <>获得结果?

[英]How to get the result from Task.Factory.StartNew<>?

Please let me know if I can run more than one Task.Factory.StartNew statement in parallel. 如果我可以并行运行多个Task.Factory.StartNew语句,请告诉我。

Some thing like this 有点像这样

var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId, null,"DEV"));
var task1 = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId, null, "PROD"));

If so. 如果是这样的话。 how to get the output of the statement and use it. 如何获取语句的输出并使用它。

I have used the statement like below before. 我之前使用过如下的声明。 where the application will wait till I get the output from the thread. 应用程序将等待直到我从线程获得输出。

var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId, null,"DEV"));
return (List<AccessDetails>)task.ContinueWith(tsk => accdet = task.Result.ToList()).Result;

You can let multiple tasks run, and wait for all of them to be finished like this: 您可以让多个任务运行,并等待所有这些任务完成,如下所示:

var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId, null,"DEV"));        
var task1 =  Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(mirrorId, null, "PROD"));  

var allTasks = new Task[]{task, task1};

Task.WaitAll(allTasks);

var result = task.Result;
var result1 = task1.Result;    

If you want to just wait for the first one to finish, you can use Task.WaitAny for example. 如果您只想等待第一个完成,可以使用Task.WaitAny作为示例。

you can easily run more than one task 您可以轻松地运行多个任务

you can use Task Result MSDN Example 您可以使用任务结果MSDN示例

you can create an object which can hold you resullts pass it to the task and update it should look something like this 你可以创建一个可以阻止你重新组合的对象将它传递给任务并更新它应该看起来像这样

MyResultObeject res = new MyResultObject 
var task = Task.Factory.StartNew<List<AccessDetails>>(() => this.GetAccessListOfMirror(res,mirrorId, null,"DEV"));

just dont forget to check whether the task has finished 只是不要忘记检查任务是否已完成

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

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