Setting the field value in try {} and calling the base class in finally {}

I was looking at the source code of the .NET Framework, trying to understand another problem, and I saw this code (in PeerNearMe.csfrom 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 a reason to put a variable assignment in a block try? Could this go astray in any way? At first I thought, because finally it will be executed, even if the thread is interrupted with Thread.Abort():

Unfinished finally blocks are executed before the thread is interrupted.

In this case, I expect to try to block the inclusion of the whole body of the method:

try {
    if (!m_disposed)
        m_disposed = true;
}
finally {
    base.Dispose(disposing)
}

However, they also say:

, Abort, , , , , catch, finally block . , Abort, , , .

, , .

: ? ? - Thread.Abort(), ?

: - Thread.Abort(), , if (!m_Disposed) {, try {. , Dispose() ( , ).

+4
2

, , - - Thread.Abort - , , Thread.Interrupt OutOfMemoryException.

, base.Dispose , - .

Thread.Abort - , m_disposed = true , . , - , , ( ).

finally Thread.Abort - . base.Dispose finally, , , , , ( , finally, - - finally).

- . , , , Dispose, :) Dispose , finally - - , . , Dispose - , .

, , , using, , using, Dispose finally!

using (var bmp = new Bitmap())
{
  ...
}

Bitmap bmp = null;
try
{
  bmp = new Bitmap();

  ...
}
finally
{
  if (bmp != null) bmp.Dispose();
}

, , :)

+4

, , , , - .

, . , , if (! M_disposed) , Dispose, m_disposed , dispose m_disposed.

0

Source: https://habr.com/ru/post/1614412/


All Articles