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.

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Using List<string> result = await GetStringListAsync(); tell me await operator can only be used with async method. I cant understand why since it is async method.
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.
I found my final doubt in a stackoverflow question that you answered as well. stackoverflow.com/questions/11836325/…. Thanks you very much for your help dude.
Main cannot be async. You have a couple of options: you can install a SynchronizationContext (described on my blog) or you can create an async Task MainAsync method and synchronously block on it from Main: MainAsync().Wait();
You are a Master! Thanks again. Will take a look at your blog periodically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.