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

12,628

Solution 1

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.

Solution 2

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

Share:
12,628
smv
Author by

smv

Updated on June 15, 2022

Comments

  • smv
    smv almost 2 years

    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;