C # waits for a group of tasks but returns objects

Just a quick question. I believe this is just a quick syntax question. Below I am posting 3 threads and for testing multithreading. I just have methods that return int, not using them for anything.

Now I'm trying to go further with this and return data with every stream sent. However, I obviously cannot say "datatable dt = tasks.Add (.... etc.)

So how would I send all 3 threads at the same time and give me 3 returned data? Would I use something other than an array?

Edit. I don't think I explain myself well. I apologize. All I do is each method (nrx.nzrxin, ni.nzinputins) returns the returned datatable. I just don't know the syntax for sending a method on a stream. Usually you do "datatable dt = nrz.nzrxins". How do you do it with the task?

Thank,

NZInput NI = new NZInput();
NZOutput NO = new NZOutput();
NZRX NRX = new NZRX();


List<Task> tasks = new List<Task>(3);

tasks.Add(Task.Run(() => NRX.nzrxins()));
tasks.Add(Task.Run(() => NI.nzinputins()));
tasks.Add(Task.Run(() => NO.nzoutputins()));

Task.WaitAll(tasks.ToArray());

      

+3


source to share


3 answers


You can easily collect all the results using Task.WhenAll

:

var results = await Task.WhenAll(tasks);

      



If you need synchronous version: Task.WhenAll(tasks).Result

.

It's worth taking some time to get to know all the common TPL helper methods.

+5


source


Get results. Plain.



NZInput NI = new NZInput();
NZOutput NO = new NZOutput();
NZRX NRX = new NZRX();


var tasks = new[]{
    Task.Run(() => NRX.nzrxins()),
    Task.Run(() => NI.nzinputins()),
    Task.Run(() => NO.nzoutputins())),
};

Task.WaitAll(tasks);

var nrxResult = tasks[0].Result;
var niResult = tasks[1].Result;
var noResult = tasks[2].Result;

      

+3


source


Check the Result property of each task after it completes. Note that exceptions will bubble at this point.

+2


source







All Articles