我注意到在 System.Threading.TimerBase.Dispose()
中,该方法有一个 try{} finally{}
block ,但是 try{}
为空。
将 try{}finally{}
与空的 try
一起使用有什么值(value)吗?
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal bool Dispose(WaitHandle notifyObject)
{
bool status = false;
bool bLockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
do {
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0) {
bLockTaken = true;
try {
status = DeleteTimerNative(notifyObject.SafeWaitHandle);
}
finally {
m_lock = 0;
}
}
Thread.SpinWait(1);
// yield to processor
}
while (!bLockTaken);
GC.SuppressFinalize(this);
}
return status;
}
最佳答案
来自 http://blog.somecreativity.com/2008/04/10/the-empty-try-block-mystery/ :
This methodology guards against a Thread.Abort call interrupting the processing. The MSDN page of Thread.Abort says that “Unexecuted finally blocks are executed before the thread is aborted”. So in order to guarantee that your processing finishes even if your thread is aborted in the middle by someone calling Abort on your thread, you can place all your code in the finally block (the alternative is to write code in the “catch” block to determine where you were before “try” was interrupted by Abort and proceed from there if you want to).
关于c# - 为什么要在空 try block 中使用 try {} finally {}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2186101/