3

Just a quick question. I believe this is just a quick syntax question. Below I'm sending out 3 threads and for testing multi-threading I just have the methods returning an int, not using them for anything.

Now, I am trying to go further with this and return a datatable with each thread sent out. However, I obviously can't say 'datatable dt = tasks.Add(....etc.'

So how would I send out all 3 threads at the same time and get the 3 datatables returned to me? Would I use something other than an array?

Edit- I think I'm not explaining myself well I apologize. All I'm doing is each method( nrx.nzrxin, ni.nzinputins) returns a datatable. I just don't know the syntax for sending the method out in a thread. Usually you would do 'datatable dt = nrz.nzrxins'. How do you do that with a task?

Thanks,

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());
0

3 Answers 3

5

You can easily collect all results by using Task.WhenAll:

var results = await Task.WhenAll(tasks);

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

It is worth spending some time to get to know all the common TPL helper methods.

Sign up to request clarification or add additional context in comments.

Comments

3

Get the results. Simple.

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;

1 Comment

Thanks this is what I was looking for! Appreciate it!
2

Check the Result property of each task once they have finished. Note that exceptions will bubble up at this point.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.