简体   繁体   中英

Best design pattern to handle Task Results ( await / async )

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.

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 (eg, 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM