[英]Unable to catch async/await Task exception
I have a fire and forget method(its there for legacy purpose), 我有一种解雇方法(用于遗留目的),
BackgroundWorker.Run(() => {
// my code here that throws an error
});
I don't wanna await BackgroundWorker.Run
. 我不想等待BackgroundWorker.Run
。 Here is my class, 这是我的课,
public class BackgroundWorker
{
public static Task Run(Action action)
{
return new IISBackgroundTask().DoWorkAsync(action);
}
class IISBackgroundTask : IRegisteredObject
{
public IISBackgroundTask()
{
HostingEnvironment.RegisterObject(this);
}
void IRegisteredObject.Stop(bool immediate)
{
if (_task.IsCompleted || _task.IsCanceled || _task.IsFaulted || immediate)
{
HostingEnvironment.UnregisterObject(this);
}
}
public async Task DoWorkAsync(Action action)
{
try
{
_task = Task.Run(action);
await _task;
}
catch (AggregateException ex)
{
// Log exceptions
foreach (var innerEx in ex.InnerExceptions)
{
Logger.Log(innerEx);
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
private Task _task;
}
}
I am unable to catch exception. 我无法捕捉到异常。
Update: If I add await at BackgroundWorker.Run
then it will work but I wanna fire and forget. 更新:如果我在BackgroundWorker.Run
添加一个wait,它将可以正常工作,但是我想开火并忘记。
For now I have fixed it using, 目前,我已经使用
public void DoWork(Action action)
{
_task = Task.Run(() =>
{
try
{
action();
}
catch (AggregateException ex)
{
foreach (var innerEx in ex.InnerExceptions)
{
Logger.Log(innerEx);
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.