Pete
Pete

Reputation: 15

Return value from System.Threading.Task-Method?

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...

Upvotes: 1

Views: 626

Answers (1)

user7116
user7116

Reputation: 64068

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])),
};

Upvotes: 2

Related Questions