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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With