【发布时间】:2023-03-14 01:51:01
【问题描述】:
在下面的方法中,当 TRY 块中抛出异常时,它正在被吞噬。我怎样才能让它抛出异常,以便将其写入到 catch 块中?日志编写器工作正常。谢谢!
public static bool MonitorQueueEmptyTask(string queueName, CancellationTokenSource tokenSource)
{
try
{
Task<bool> task = Task.Factory.StartNew<bool>(() =>
{
while (!QueueManager.IsQueueEmpty(queueName))
{
if (tokenSource.IsCancellationRequested)
{
break;
}
Thread.Sleep(5000);
throw new Exception("Throwing an error!"); //THIS THROW IS SWALLOWED -- NO LOG WRITTEN ON CATCH
};
return true;
}, tokenSource.Token);
}
catch (Exception ex)
{
WriteExceptionToLog(ex.Stack); //it's not that this method doesn't work. it works fine.
return false;
}
return true;
}
【问题讨论】:
-
你能把try/catch放在任务块里吗?
-
这行不通,因为外线程退出try时任务可能还没有完成。
-
谢谢大家!尝试捕获 AggregateException,尝试将 try/catch 移入内部。聚合捕获不起作用,并且将尝试移到内部起作用,但是仅在调试完成后才会发生日志记录。我有这个设置:
在配置中,显然这应该在调试时强制抛出。它没有。 -
我应该补充一下,这是一种长时间的运行方法,我不能等待。这有点像火,然后忘记,让它做它的事情,但必要时扔掉。
标签: c# .net exception task-parallel-library task