views:

141

answers:

4

Consider the following code:

// module level declaration
Socket _client;

void ProcessSocket() {
    _client = GetSocketFromSomewhere();
    using (_client) {
        DoStuff();  // receive and send data

        Close();
    }
}

void Close() {
    _client.Close();
    _client = null;
}

Given that that the code calls the Close() method, which closes the _client socket and sets it to null, while still inside the `using' block, what exactly happens behind the scenes? Does the socket really get closed? Are there side effects?

P.S. This is using C# 3.0 on the .NET MicroFramework, but I suppose the c#, the language, should function identically. The reason i am asking is that occasionally, very rarely, I run out of sockets (which is a very precious resource on a .NET MF devices).

+1  A: 

using just translates to a simple try/finally where in the finally block _client.Dispose() is called if _client isn't null.

so since you close _client and set it to null, the using doesn't really do anything when it closes.

Joel
Here's an answer on SOF that is similar that describes what is happening: http://stackoverflow.com/questions/278902/using-statement-vs-try-finally/278924#278924
Joel
This answer is misleading. What _client is set to is at the time the dispose happens is irrelevant; the original value is what is disposed.
Eric Lippert
+5  A: 

Dispose will still be called. All you are doing is pointing the variable _client to something else in memory (in this case: null). The object that _client intially referred to will still be disposed at the end of the using statement.

Run this example.

class Program
{
    static Foo foo = null;

    static void Main(string[] args)
    {
        foo = new Foo();

        using (foo)
        {
            SomeAction();
        }

        Console.Read();
    }

    static void SomeAction()
    {
        foo = null;
    }
}

class Foo : IDisposable
{
    #region IDisposable Members

    public void Dispose()
    {
        Console.WriteLine("disposing...");
    }

    #endregion
}

Setting the variable to null is not destroying the object or preventing it from being disposed by the using. All you are doing is changing the reference of the variable, not changing the object originally referenced.

Late edit:

Regarding a discussion from the comments about MSDN's using reference http://msdn.microsoft.com/en-us/library/yh598w02.aspx and the code in the OP and in my example, I created a simpler version of the code like this.

Foo foo = new Foo();
using (foo)
{
    foo = null;
}

(And, yes, the object still gets disposed.)

You could infer from the link above that the code is being rewritten like this:

Foo foo = new Foo();
{
    try
    {
        foo = null;
    }
    finally
    {
        if (foo != null)
            ((IDisposable)foo).Dispose();
    }
}

Which would not dispose the object, and that does not match the behavior of the code snippet. So I took a look at it through ildasm, and the best I can gather is that the original reference is being copied into a new address in memory. The statement foo = null; applies to the original variable, but the call to .Dispose() is happening on the copied address. So here is a look at how I believe the code is actually being rewritten.

Foo foo = new Foo();
{
    Foo copyOfFoo = foo;
    try
    {
        foo = null;
    }
    finally
    {
        if (copyOfFoo != null)
            ((IDisposable)copyOfFoo).Dispose();
    }
}

For reference, this is what the IL looks like through ildasm.

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       29 (0x1d)
  .maxstack  1
  .locals init ([0] class Foo foo,
           [1] class Foo CS$3$0000)
  IL_0000:  newobj     instance void Foo::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  stloc.1
  .try
  {
    IL_0008:  ldnull
    IL_0009:  stloc.0
    IL_000a:  leave.s    IL_0016
  }  // end .try
  finally
  {
    IL_000c:  ldloc.1
    IL_000d:  brfalse.s  IL_0015
    IL_000f:  ldloc.1
    IL_0010:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
    IL_0015:  endfinally
  }  // end handler
  IL_0016:  call       int32 [mscorlib]System.Console::Read()
  IL_001b:  pop
  IL_001c:  ret
} // end of method Program::Main

I don't make a living staring at ildasm, so my analysis can be classified as caveat emptor. However, the behavior is what it is.

Anthony Pegram
I'm sorry, but the down vote is incorrect. But, OK, rewrite it. My point still stands. I'll post the code that matches his example if that will help.
Anthony Pegram
@Ben, thanks for the reconsideration. ;)
Anthony Pegram
Well, your first example was clearly wrong. But so was my second comment (which I deleted). :-) In my defense, the reference is a bit misleading -- http://msdn.microsoft.com/en-us/library/yh598w02.aspx; see the `if (var != null)` part -- but I tested it, and you're right.
Ben M
If it helps to not confuse things, I'll remove the original snippet. You're right in that it didn't match his program exactly, although the result is the same.
Anthony Pegram
@Ben, that link is interesting. I rewrote the using statement to match the implementation MSDN referred to, and sure enough .Dispose() was not called (keeping foo referring to the instance of Foo created earlier in the code). I'll leave it up to language gurus to possibly explain how and why the MSDN documentation does not match the example code here, because I'm not one to have the language spec committed to memory!
Anthony Pegram
This compiler warning adds a little detail http://msdn.microsoft.com/en-us/library/zhdyhfk6.aspx
Brian Rasmussen
My post crossed your latest update, but I have posted a commented version of the IL for the ProcessSocketMethod.
Brian Rasmussen
+2  A: 

As Anthony pointed out Dispose() will be called even if the reference is nulled during the execution of the using block. If you take a look at the generated IL, you'll see that even tough ProcessSocket() uses an instance member to store the field, a local reference is still created on the stack. It is via this local reference that Dispose() is called.

The IL for ProcessSocket() looks like this

.method public hidebysig instance void ProcessSocket() cil managed
{
   .maxstack 2
   .locals init (
      [0] class TestBench.Socket CS$3$0000)
   L_0000: ldarg.0 
   L_0001: ldarg.0 
   L_0002: call instance class TestBench.Socket     TestBench.SocketThingy::GetSocketFromSomewhere()
   L_0007: stfld class TestBench.Socket TestBench.SocketThingy::_client
   L_000c: ldarg.0 
   L_000d: ldfld class TestBench.Socket TestBench.SocketThingy::_client
   L_0012: stloc.0 
   L_0013: ldarg.0 
   L_0014: call instance void TestBench.SocketThingy::DoStuff()
   L_0019: ldarg.0 
   L_001a: call instance void TestBench.SocketThingy::Close()
   L_001f: leave.s L_002b
   L_0021: ldloc.0 
   L_0022: brfalse.s L_002a
   L_0024: ldloc.0 
   L_0025: callvirt instance void [mscorlib]System.IDisposable::Dispose()
   L_002a: endfinally 
   L_002b: ret 
   .try L_0013 to L_0021 finally handler L_0021 to L_002b
}

Notice the local and notice how this is set to point to the member on lines L_000d-L_0012. The local is loaded again in L_0024 and used to call Dispose() in L_0025.

Brian Rasmussen
Glad to not be the only one staring at the IL disassembler!
Anthony Pegram
+4  A: 

I suppose you could figure this out by looking at the disassembly, but it's a lot easier to just read section 8.13 of the specification, where all these rules are clearly described.

Reading those rules makes it clear that the code

_client = GetSocketFromSomewhere(); 
using (_client) 
{ 
    DoStuff();
    Close(); 
} 

is transformed by the compiler into

_client = GetSocketFromSomewhere();
{
    Socket temp = _client;
    try 
    { 
        DoStuff();
        Close(); 
    }
    finally
    {
        if (temp != null) ((IDispose)temp).Dispose();
    }
}

So that's what happens. The socket gets disposed twice in the non-exceptional code path. This strikes me as probably not fatal, but definitely a bad smell. I'd write this as:

_client = GetSocketFromSomewhere();
try 
{ 
    DoStuff();
}
finally
{
    Close();
}

It's perfectly clear that way and nothing gets double-closed.

Eric Lippert
That's a great deal easier to read than my IL dump. Thanks. Why didn't I just look it up in the spec.
Brian Rasmussen