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

Please let me know if I can run more than one Task.Factory.StartNew statement Task.Factory.StartNew parallel.

Something like that

 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 instruction and use it.

I used the instructions as shown below. where the application will wait while I get output from the stream.

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

You can start several tasks and wait for the completion of all these actions as follows:

 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 just want to wait for the first to complete, you can use Task.WaitAny , for example.

+12
source

you can easily run multiple tasks

you can use Task Result MSDN Example

you can create an object that can hold you, sends it to the task and updates it should look something like this.

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

just remember to check if the task is over

+1
source

Source: https://habr.com/ru/post/944105/


All Articles