1

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.

Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82

1 Answers1

1

Use await instead of ContinueWith or Result:

try
{
  List<string> area = await GetStringListAsync();
  area.ForEach((y) => Console.WriteLine(y));
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}

As a side note, you should usually not wrap synchronous methods (GetStringList) with a fake-asynchronous methods (e.g., using Task.Run). Let the caller decide if they want to push it to a background thread:

try
{
  List<string> area = await Task.Run(() => GetStringList());
  area.ForEach((y) => Console.WriteLine(y));
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Using List result = await GetStringListAsync(); tell me await operator can only be used with async method. I cant understand why since it is async method. – Carlos Landeras Jul 03 '13 at 12:47
  • It's talking about the code that has the `await` in it. *That* method also needs to be `async`. Yes, this will cause a "chain reaction" as `async` grows through your code base. – Stephen Cleary Jul 03 '13 at 12:48
  • I found my final doubt in a stackoverflow question that you answered as well. http://stackoverflow.com/questions/11836325/await-operator-can-only-be-used-within-an-async-method. Thanks you very much for your help dude. – Carlos Landeras Jul 03 '13 at 13:02
  • Main cannot be `async`. You have a couple of options: you can install a SynchronizationContext [(described on my blog)](http://blog.stephencleary.com/2012/02/async-console-programs.html) or you can create an `async Task MainAsync` method and synchronously block on it from `Main`: `MainAsync().Wait();` – Stephen Cleary Jul 03 '13 at 13:03
  • You are a Master! Thanks again. Will take a look at your blog periodically. – Carlos Landeras Jul 03 '13 at 13:05