【问题标题】:Best design pattern to handle Task Results ( await / async )处理任务结果的最佳设计模式(等待/异步)
【发布时间】:2013-07-04 13:58:08
【问题描述】:

我刚刚安装了 Visual Studio 2012,所以我终于可以测试 C# 5.0 的功能了 像异步/等待。我正在做一些测试,我想到了一个疑问。 处理任务结果的最佳方式是什么。

鉴于以下片段:

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" };

        }

我正在处理ContinueWith 中的任务结果,但我想知道是否有更好的 方法。

【问题讨论】:

    标签: c# .net asynchronous task


    【解决方案1】:

    使用await 代替ContinueWith 或Result:

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

    作为旁注,您 should usually not wrap synchronous methods (GetStringList) with a fake-asynchronous methods(例如,使用 Task.Run)。让调用者决定是否要将其推送到后台线程:

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

    【讨论】:

    • 使用列表 结果 = await GetStringListAsync();告诉我 await 运算符只能与 async 方法一起使用。我不明白为什么,因为它是异步方法。
    • 它谈论的是其中包含await 的代码。 那个方法也需要是async。是的,随着async 在您的代码库中不断增长,这将导致“连锁反应”。
    • 我在你回答的一个 stackoverflow 问题中发现了我的最后一个疑问。 stackoverflow.com/questions/11836325/…。非常感谢你的帮助伙计。
    • 主要不能是async。你有几个选择:你可以安装一个 SynchronizationContext (described on my blog) 或者你可以创建一个 async Task MainAsync 方法并从 Main 同步阻止它:MainAsync().Wait();
    • 你是大师!再次感谢。会定期查看您的博客。
    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多