Can CLR-targeted compilers generate a call to the Dispose method when an object is null?

Can a compiler (for example, C #) automatically generate a call to the Dispose method for an object when it is set to null (of course, the object must support the Dispose method in the first place). For example, if we write

cnSqlConnection = null;

and cnSqlConnection is an instance of type SqlConnection, can the C # compiler insert an invocation of the Dispose method right before updating the null reference?

In addition, since framework classes support a scenario in which the Dispose method can be called multiple times, there would be no harm if the call is duplicated.

+3
source share
7

(a) . Dispose, , , .

(b) . : - Dispose . , , CLR, .

+7

, :
:

class A : IDisposable { public void Dispose() { } }

1:

IDisposable a = new A();
IDisposable b = a;
a = null; // The object is still alive in b, should it really be disposed?

2:

IDisposable a = new A();
IDisposable b = new A();
a = b; // a is not accessible anymore, but not set to null, 
       //shouldn't it be disposed here?

3:

private void Foo()
{
    IDisposable a = new A();
    // a is not used any more, but not set to null, 
    //shouldn't it be disposed here?
}

# using, , :

using (IDisposable a = new A())
{
    // Do stuff
}   // Here a.Dispose() is automatically called.
+4

, , , .

, , - , . , ( , , ).

, . GC , null ( ). , GCed, IDisposable, Dispose. CLR .

, ( ), COM, . - , GC- CLR.

-, : , , IDisposable, . , , , Dispose , ( ).

+2

, . , , . .

, , , . . , , .

IDisposable() , . , , . , Dispose() . , COM-.

. , , . , . Microsoft , CLR. . GC .

+2

, Dispose. , . , , .

.

void DoSomething(IDisposable disposable)
{
  DoSomethingElse(disposable);
  disposable = null;
}

, DoSomethingElse disposable DoSomething - ? , , , "".

- , IDisposable Dispose, , . , , ? .

  • ?
  • ?
  • ?

, , . , ? , , , . .

blog .

+1
public static class MissingCompilerFeatures
{
    public static void SetToNullAndDispose(ref IDisposable obj)
    {
        if (obj != null) { obj.Dispose(); obj = null; }
    }
}
0

null , , Dispose . IDisposable, Dispose(), , using.

IDisposable garbage:

http://www.xtremedotnettalk.com/showthread.php?t=97910

0
source

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


All Articles