1

I have a doubt with Using(){}. I know that it uses Idisposable interface. So if I write in linq to entities:

Using(objectconext context=new objectcontext())
{
   throw new Exception();
}

will the objectcontext still be disposed and the existing connection be closed or it will remain there alive. Thanks, Gaurav

tereško
  • 58,060
  • 25
  • 98
  • 150
Gaurav Pandey
  • 2,798
  • 4
  • 28
  • 41

6 Answers6

2

The connection won't necessarily be closed, as this is managed elsewhere.

spender
  • 117,338
  • 33
  • 229
  • 351
  • Hi spender, thanks for your time. What should be the best practice then when using entity framework? – Gaurav Pandey Apr 11 '11 at 16:02
  • The Context should be regarded as ephemeral. The framework is designed so that you can use them in a very throw-away fashion. Connections are pooled and reused. Your usage is fine. – spender Apr 11 '11 at 16:11
1

The using statement expands to a try finally block. So when the exception is thrown, the finally block in the using statement should execute.

From http://msdn.microsoft.com/en-us/library/yh598w02.aspx:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

What happens next is another matter. As spender points out in his answer, the DataContext has no obligation to close the connection it is using, nor do you need to be concerned about it (since the DataContext should properly manage the connection for you).

Under certain conditions, your thrown exception can be swallowed silently by the try finally block. See here: http://www.digitallycreated.net/Blog/51/c%23-using-blocks-can-swallow-exceptions. This shouldn't affect you, though.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • @paolo: You should be OK as long as Dispose doesn't throw an exception. If that happens, the exception thrown by Dispose takes precedence (which is proper, IMO). – Robert Harvey Apr 11 '11 at 16:18
1

From try-finally on MSDN:

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

Since "using" is syntactic sugar for a try {} finally { /*calling IDisposable.Dispose() */ } block, using should guarantee that your object is properly disposed even in case of exception.

Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
1

Because your are using USING keyword it will be disposed even if there is an exception.

It's discussed in this thread: C# "Using" Syntax

Community
  • 1
  • 1
Afshin Gh
  • 7,918
  • 2
  • 26
  • 43
0

Yes it will be disposed. Using is similar like Try-Catch-Finally and disposal of objects in Finally block.

Anuraj
  • 18,859
  • 7
  • 53
  • 79
0

Dispose will close the connection if it was opened by the Entity Framework.

BrandonZeider
  • 8,014
  • 2
  • 23
  • 20