Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task Results into a Single list

I have a method below in my WCF service:

public List<string> ProcessTask(IEnumerable<string> data)
{             
    var contentTasks = ..........
    List<string> contentWeb = new List<string>();

    Task.Factory.ContinueWhenAll(contentTasks, tasks =>
    {
        foreach (var task in tasks)
        {
            if (task.IsFaulted)
            {
                Trace.TraceError(task.Exception.GetBaseException().Message);
                continue;
            }

            if (task.Result == null || String.IsNullOrEmpty(task.Result.Content))
            {
               continue;
            }

            contentWeb.Add(task.Result.Content);
        }
    });
}

How do I return the List of strings that have Result.Content from all the tasks? These tasks are asynchronous tasks, so basically I have to wait until all tasks are done before I return the result.

like image 409
Justin Homes Avatar asked Mar 02 '26 02:03

Justin Homes


1 Answers

You should return a Task<List<string>>:

public Task<List<string>> ProcessTasksAsync(IEnumerable<string> data)
{
    var contentTasks = ..........
    return Task.Factory.ContinueWhenAll(contentTasks, tasks =>
    {
        var contentWeb = new List<string>(); // Build this in the continuation
        foreach (var task in tasks)
        {
            // ...same code...

            contentWeb.Add(task.Result.Content);

        }
        return contentWeb; // Set the task's result here
    });
}

As this is a WCF service, you can use the Task<T> method to implement an asynchronous method pair by returning the Task<T> in the Begin*** method, and unwrapping the Task<T> in the End*** method.

This makes this method asynchronous in a proper manner.

Note that this is far easier in C# 5 using async/await:

public async Task<List<string>> ProcessTasksAsync(IEnumerable<string> data)
{
    var contentTasks = ..........

    await Task.WhenAll(contentTasks);

    var contentWeb = new List<string>(); // Build this in the continuation
    foreach (var task in contentTasks)
    { 
        // ...same code...

        contentWeb.Add(task.Result.Content);
    }

    return contentWeb;
}
like image 195
Reed Copsey Avatar answered Mar 04 '26 15:03

Reed Copsey