I was browsing .NET Framework source code trying to understand another issue and I saw this code (in PeerNearMe.cs
from System.Net.PeerToPeer.Collaboration
):
private bool m_Disposed;
protected override void Dispose(bool disposing)
{
if (!m_Disposed){
try{
m_Disposed = true;
}
finally{
base.Dispose(disposing);
}
}
}
Is there any reason to put variable assignment in try
block? May it fail in any way with an exception?! At first I thought it's because finally will be executed even if thread is aborted with Thread.Abort()
:
Unexecuted finally blocks are executed before the thread is aborted.
In this case I'd expect try block to include all method body:
try {
if (!m_disposed)
m_disposed = true;
}
finally {
base.Dispose(disposing)
}
However they also says:
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.
IMO calling a base class virtual method is little bit a jump in the dark in this case.
In short: what's this point of that code? What it really tries to implement? If it's because of Thread.Abort()
then isn't it just wrong?
EDIT: if it's really just because of Thread.Abort()
then it doesn't do its job if abort happens after if (!m_Disposed) {
but before try {
. Note that Dispose()
must be resilient to multiple calls and simply do nothing (regardless when it's called).