1

I'm creating an array of 5 tasks invoking the string-returning method "Essen"

 tasks[0] = new Task(() => Philosoph.Essen("1", gabeln[2], gabeln[1])); tasks[1] = new Task(() => Philosoph.Essen("2", gabeln[3], gabeln[2])); tasks[2] = new Task(() => Philosoph.Essen("3", gabeln[4], gabeln[3])); tasks[3] = new Task(() => Philosoph.Essen("4", gabeln[5], gabeln[4])); tasks[4] = new Task(() => Philosoph.Essen("5", gabeln[1], gabeln[5])); 

Then I'm starting these Tasks using Parallel.ForEach

 Parallel.ForEach(tasks, t => { t.Start(); }); Task.WaitAll(tasks); 

Method Essen is returning String

 static public string Essen(String philosoph, String linkeGabel, String rechteGabel) { lock (linkeGabel) { lock (rechteGabel) { return ("Philosoph " + philosoph + "isst mit: " + linkeGabel + ", " + rechteGabel ); } } } 

How can I process Essen()-Return value at each of the 5 parallel processings? I'd like to write these return values into a listbox...

1
  • Ehmm.. you're spinning up 5 tasks, just to call a method that returns a string (no 'work' code?), 5 times? ... Seems like you might get better performance, just doing it synchronously on the current thread. Commented Jun 5, 2013 at 17:57

1 Answer 1

2

You use ContinueWhenAll:

// once tasks are started TaskFactory.ContinueWhenAll( tasks, results => { foreach (var t in results) { if (t.IsCompleted) listBox.Items.Add(t.Result); } }, cts.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); 

Be sure to use the correct scheduler for your ListBox. Also, you need to be sure you "observe" any Task<TResult>.Exception that may have occurred (i.e. if t.IsFaulted check out t.Exception).

However, currently your tasks are not defined to return anything. You need to change their definition to be Task<TResult>:

// will use the return type of Philosoph.Essen, which is string // Task<string>[] tasks; var tasks = new [] { Task.Factory.StartNew(() => Philosoph.Essen("1", gabeln[2], gabeln[1])), Task.Factory.StartNew(() => Philosoph.Essen("2", gabeln[3], gabeln[2])), Task.Factory.StartNew(() => Philosoph.Essen("3", gabeln[4], gabeln[3])), Task.Factory.StartNew(() => Philosoph.Essen("4", gabeln[5], gabeln[4])), Task.Factory.StartNew(() => Philosoph.Essen("5", gabeln[1], gabeln[5])), }; 
Sign up to request clarification or add additional context in comments.

1 Comment

You need to change your definition of the tasks to be a Task<string> instead of just Task.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.