问题描述
我在从 Task.Run
捕获异常时遇到问题,通过如下更改代码解决了该问题.我想知道这两种方式处理异常的区别:
I had a problem with catching the exception from Task.Run
which was resolved by changing the code as follows. I'd like to know the difference between handling exceptions in these two ways :
在 Outside
方法中我无法捕获异常,但在 Inside
方法中我可以.
In the Outside
method I can't catch the exception, but in the Inside
method I can.
void Outside()
{
try
{
Task.Run(() =>
{
int z = 0;
int x = 1 / z;
});
}
catch (Exception exception)
{
MessageBox.Show("Outside : " + exception.Message);
}
}
void Inside()
{
Task.Run(() =>
{
try
{
int z = 0;
int x = 1 / z;
}
catch (Exception exception)
{
MessageBox.Show("Inside : "+exception.Message);
}
});
}
推荐答案
当任务运行时,它抛出的任何异常都会被保留,并在等待任务结果或任务完成时重新抛出.
When a task is run, any exceptions that it throws are retained and re-thrown when something waits for the task's result or for the task to complete.
>
Task.Run()
返回一个 Task
对象,您可以使用它来执行此操作,因此:
Task.Run()
returns a Task
object that you can use to do that, so:
var task = Task.Run(...)
try
{
task.Wait(); // Rethrows any exception(s).
...
对于较新版本的 C#,您可以使用 await
而不是 Task.Wait():
For newer versions of C# you can use await
instead ot Task.Wait():
try
{
await Task.Run(...);
...
更整洁.
为了完整起见,这里有一个可编译的控制台应用程序,它演示了 await
的使用:
For completeness, here's a compilable console application that demonstrates the use of await
:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
test().Wait();
}
static async Task test()
{
try
{
await Task.Run(() => throwsExceptionAfterOneSecond());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static void throwsExceptionAfterOneSecond()
{
Thread.Sleep(1000); // Sleep is for illustration only.
throw new InvalidOperationException("Ooops");
}
}
}
这篇关于如何处理 Task.Run 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!