从Task.Run返回值

时间:2020-02-23 12:06:04

标签: c# xml async-await

我正在使用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);
        }

1 个答案:

答案 0 :(得分:3)

我想这就是你想要的:

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