在下面的方法中,当在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;
}
MSDN - [如何:处理由任务引发的异常(https://msdn.microsoft.com/en-us/library/dd537614.aspx) –
您能放置的try/catch在任务块? – IllidanS4
这不能工作,因为当外线程退出try时任务可能没有完成。 – usr