c# - 如何使用 await 关键字获取 Task 的数据?

标签 c# task-parallel-library .net-4.5 async-await c#-5.0

我只需要在主代码中获取 FlowDocument...

我喜欢这个,但没有成功

this.flowDoc = engine.CreateFlowDocument(contentItems); // Can't compile
 public async Task<FlowDocument> CreateFlowDocument(ContentItems contentItems)
 {   return await Task.Run(() =>
     {
         try
         {
             var fd = new FlowDocument();
             foreach (var item in contentItems.Items)
             {
                 if (item.ContentType == ContentTypes.Header)
                 {
                     var paraHeader = new Paragraph();  
                     paraHeader.FontSize = 14;
                     paraHeader.Foreground = Brushes.Black;
                     paraHeader.FontWeight = FontWeights.Bold;
                     paraHeader.Inlines.Add(new Run(item.Data));
                     fd.Blocks.Add(paraHeader);
                 }
                 if (item.ContentType == ContentTypes.Paragraph)
                 {
                      var paragraph = new Paragraph();
                      paragraph.FontSize = 12;
                      paragraph.Foreground = Brushes.Black;
                      paragraph.FontWeight = FontWeights.Normal;
                      paragraph.Inlines.Add(new Run(item.Data));
                      fd.Blocks.Add(paragraph);
                 }
             }                     
             return fd;
          }
          catch (Exception)     {                        }
          return new FlowDocument();
      }
                                 );
}

最佳答案

您需要等待从 CreateFlowDocument 返回的任务:

 this.flowDoc = await engine.CreateFlowDocument(contentItems);

当然,这意味着代码也必须在异步函数中。

如果您不希望它在异步方法中,您可以使用Result 属性,但只这样做非常小心 - 这是一个阻塞调用,您很容易陷入僵局。

或者您可以使用 Task.ContinueWith 附加一个延续.

关于c# - 如何使用 await 关键字获取 Task 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15972701/

相关文章:

c# - 应用程序之间的 Windows 目录大小差异

c# - 异步等待性能 - 直接方法调用与任务包装器调用

c# - 为什么分配任务然后等待它允许并行运行

c# - 'await' 运算符只能与异步 lambda 表达式一起使用

c# - 无法加载文件或程序集 Microsoft.Owin.Security.OAuth,版本 = 2.0.0.0

c# - 删除托 pipe 列表的最佳方法。一对多/父子关系

c# - Excel Vsto 应用程序在 Excel 2016 中无法正常工作

c# - 将 ThreadStatic 字段与任务一起使用

c# - "ListViewItemPlaceholderBackgroundThemeBrush"位于何处?

c# - 打开 RandomAccessStream 时为 "Value does not fall within the expected range"