我有一些代码,在新线程上抛出异常,我需要在主线程上确认和处理。为了实现这一点,我通过使用保存抛出异常的字段来共享线程之间的状态。
我的问题是 检查null时是否需要使用锁 正如我在下面的代码示例中所做的那样?
public class MyClass
{
readonly object _exceptionLock = new object();
Exception _exception;
public MyClass()
{
Task.Run(() =>
{
while (CheckIsExceptionNull())
{
// This conditional will return true if 'something has gone wrong'.
if(CheckIfMyCodeHasGoneWrong())
{
lock(_exceptionLock)
{
_exception = new GoneWrongException();
}
}
}
});
}
bool CheckIsExceptionNull() // Is this method actually necessary?
{
lock (_exceptionLock)
{
return _exception == null;
}
}
// This method gets fired periodically on the Main Thread.
void RethrowExceptionsOnMainThread()
{
if (!CheckIsExceptionNull())
{
lock (_exceptionLock)
{
throw _exception; // Does this throw need to be in a lock?
}
}
}
}
另外, 在主线程上抛出异常时是否需要使用锁?