【问题标题】:Return the value from Task.Run从 Task.Run 返回值
【发布时间】:2020-02-23 20:15:55
【问题描述】:

我正在使用 async/await 加载 XML 文件,但无法确定如何从 Task.Run 返回值“xe”。如何从下面代码所示的任务中返回此值?

 try
        {                
            Exception exceptionOut = null;

            await Task.Run(() =>
            {
                //inside
                try
                {

                    XElement xe = XElement.Load(filePath);
                }
                catch (Exception exceptionIn)
                {                        
                    exceptionOut = exceptionIn;
                }
            });            

            if (exceptionOut != null)
            {
                throw exceptionOut;
            }
        }
        catch (Exception ex)
        {
            //show the error
            MessageBox.Show(ex.Message);
        }

【问题讨论】:

  • 好吧,你最好使用XElement.LoadAsyncmethod,忘记Task.Run
  • @SirRufo 我也在文档中看到了这一点,但我没有这种方法作为选项。我正在运行最新的 Visual Studio 2019。
  • @James 为什么不呢?
  • @TomW LoadAsync 不在 XElement 类的下拉列表中??
  • 您的项目必须是 .NET Core 2 或 3 项目才能使用它。不能在 .NET Framework 项目中使用 .NET Core。

标签: c# xml async-await


【解决方案1】:

我想这就是你想要的:

try
{
    XElement xe = await Task.Run(() =>
    {
        return XElement.Load(filePath);
    });
}
catch (Exception ex)
{
    //show the error
    MessageBox.Show(ex.Message);
}

【讨论】:

  • 这可以简化为var xe = await Task.Run(() => XElement.Load(filePath));
猜你喜欢
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多