Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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;
like image 828
smv Avatar asked May 02 '13 07:05

smv


2 Answers

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.

like image 66
RoelF Avatar answered Sep 18 '22 08:09

RoelF


you can easily run more than one task

you can use Task Result MSDN Example

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

like image 38
makc Avatar answered Sep 21 '22 08:09

makc