What Is the C# Using Block and Why Should I Use It

What is the C# Using block and why should I use it?

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}

using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}

The second is easier to read and maintain.


Since C# 8 there is a new syntax for using that may make for more readable code:

using var x = new SomeDisposableType();

It doesn't have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:

string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}

And have this:

using var someReader = ...;
string x = someReader.Read();

When should I use using blocks in C#?

When the SomeType class implements IDisposable.

What are the uses of using in C#?

The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}

to

{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}

C# 8 introduces a new syntax, named "using declarations":

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

So the equivalent code of above would be:

using var myRes = new MyResource();
myRes.DoSomething();

And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

The reason we use using statement in the following code?

1) The reason for the using statement is to ensure that the myEntities.Dispose() method is called as soon as the code inside the using statement completes. This is necessary since the PlanetWroxEntities class' base class is a DbContext which holds a connection to the database.

Database connections are a precious resource that are obtained from the database connection pool and there are only a finite number of connections available that your whole application must share. If you don't call Dispose on the myEntities object as soon as you are done with it via the using statement (or some other manner) then the myEntities object will continue to tie up that database connection for some undetermined amount of time until the garbage collection code from the .net memory manager gets around to reclaiming the memory that is held by the myEntities object that is no longer in use.

The memory manager will at that time calls the dispose method. As soon as the Dispose method is called the database connection is released from the object and returned to the database connection pool where it can be obtained by other parts of your application when you make a call to get a database connection (for example when you create other instances of the PlanetWroxEntities class.)

The purpose of the using statement is to have the Dispose method called as soon as you are done with the object so that in this case the database connection is returned to the pool right away.

2) It means the database connection is released by your application and is returned to the database connection pool where it is now available to be obtained by other parts of your application. Here is one resource that talks more about connection pooling, it will give you more background on what is going on under the hood: https://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

Under the hood the using statement is implemented as a finally statement. So this code:

using (PlanetWroxEntities myEntities = new PlanetWroxEntities())    
{
var authorizedReviews = from review in myEntities.Reviews
where review.Authorized == true
orderby review.CreateDateTime descending
select review;

GridView1.DataSource = authorizedReviews.ToList();

GridView1.DataBind();
}

becomes

PlanetWroxEntities myEntities; 
try{
myEntities = new PlanetWroxEntities();
var authorizedReviews = from review in myEntities.Reviews
where review.Authorized == true
orderby review.CreateDateTime descending
select review;

GridView1.DataSource = authorizedReviews.ToList();

GridView1.DataBind();

} finally{
myEntities.Dispose();
}

In the old days of C# we always had to write the finally statement ourselves to dispose of disposable objects so that their unmanaged resources were released. But later the using statement was introduced in C# to make it easier to accomplish this. Even today, you can write the finally statement yourself if you prefer, but most people love the using statement.

For more information see https://msdn.microsoft.com/en-us/library/yh598w02.aspx

Creating a resource in the using block vs outside the using block

The first noteworthy difference is the fact that, in your first snippet, the variable resource is still declared after the using block, and so someone could use it after it was disposed, which is bad.

var resource = CreateNewResource();
using (resource)
{
//Use resource
}
...
// Unknowingly continues to use resource
resource.BadActOnDisposedObject();

If you decidedly want to use and allocate your resources more freely, I would suggest using try/finally, like so:

Resource resource = null;
try
{
// do whatever
resource = CreateNewResource();
// continue to do whatever
}
finally
{
if (resource != null)
{
resource.Dispose();
resource = null;
}
}

This guarantees that your resource is disposed in any case.

Why should I use Using block to connect to the EntityFramework Model?

You use using statements to make sure any resources you are done with get disposed of, so they don't use any memory when they don't need to. If you would have many connections to Entity Framework (EF) open (for instance), your app could consume a whole lot of memory and cause some trouble on the machine it's running on.

A using statement calls Dispose() on an object that implements IDisposable (an interface). You could avoid using the using statement by calling Dispose() explicitly. (But you might forget, so it's easy to just use the using for an object that you want to dispose once you're done with it.)

You could setup a connection in a helper class, by, for instance, using a Singleton Pattern to make sure you only ever have one object with an Entity Connection at the most. But in the case of EF this might cause other problems with tracking by EF. You could also setup a Repository (C# EF Repository Pattern) that is the only class to open and close these connections to EF and keeps it neatly in one place.

C# using blocks

using (var client = new WebClient())
using (var stream = client.OpenRead(originGetterURL))
using (var reader = new StreamReader(stream))
{
var jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
var encryptionKey = (string)jObject["key"];
var originURL = (string)jObject["origin_url"];
}

or simply:

using (var client = new WebClient())
{
var json = client.DownloadString(originGetterURL);
var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
var encryptionKey = (string)jObject["key"];
var originURL = (string)jObject["origin_url"];
}

Using the using statement in C#

The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.

    //the compiler will create a local variable 
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}

Alternatively you could just use:

    FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}

Extra reading from MSDN

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.



Related Topics



Leave a reply



Submit