【发布时间】: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