如何处理Task.Run异常 [英] How to handle Task.Run Exception
问题描述
我在从Task捕获异常时遇到问题.运行我更改了代码,问题解决了.我愿意找出以两种方式运行Task.Run中的异常之间的区别:
在Outside函数中,我无法捕获异常,但在Inside函数中,我可以捕获异常.
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);
}
});
}
运行任务时,它所引发的任何异常都将保留,并在某些等待任务结果或任务完成的情况下重新抛出. >
Task.Run()
返回一个可用于执行此操作的Task
对象,因此:
var task = Task.Run(...)
try
{
task.Wait(); // Rethrows any exception(s).
...
对于较新版本的C#,您可以使用await
而不是Task.Wait():
try
{
await Task.Run(...);
...
整整齐齐.
为完整起见,这是一个可编译的控制台应用程序,演示了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");
}
}
}
I had a problem with catching my exception from Task.Run I changed my code and my problem solved. I'm willing to figure out what is the difference between handling exceptions inside Task.Run in these two ways :
In Outside function I can't catch the exception but in Inside I can catch it.
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()
returns a Task
object that you can use to do that, so:
var task = Task.Run(...)
try
{
task.Wait(); // Rethrows any exception(s).
...
For newer versions of C# you can use await
instead ot Task.Wait():
try
{
await Task.Run(...);
...
which is much neater.
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异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!