I have just installed Visual Studio 2012, So I can finally test C# 5.0 features like async/await. I was doing some testing and a doubt come to my mind. What is the best way to handle task Results.
Given the following Snippet:
Task<List<string>> tarea = GetStringListAsync();
tarea.ContinueWith((x) =>
{
if (x.Status == TaskStatus.RanToCompletion)
{
x.Result.ForEach((y) => Console.WriteLine(y));
}
else if (x.Status == TaskStatus.Faulted)
{
Console.WriteLine(x.Exception.InnerException.Message);
}
});
private static async Task<List<string>> GetStringListAsync()
{
return await Task.Run(() =>
{
return GetStringList();
});
}
private static List<string> GetStringList()
{
//I uncomment this to get forced exception
//throw new Exception("Error Occurred");
//Add some delay
System.Threading.Thread.Sleep(12000);
return new List<string>() { "String1", "String2", "String3" };
}
I am handling the task Result in ContinueWith
, but I would like to know if there is a better aproach.