C # basics: the use of using statements

A, using statement

using new syntax elements can be regarded as .NET, it clearly shows when objects are usually a resource-intensive to use and when to start to be released manually. When using can be used, it is recommended to make use of the using statement. So far, using statement found only advantage it gives programmers without any drawbacks.

In the .NET environment, garbage collection hosted .NET resources will be released, and some unmanaged resources will need to be a programmer to manually release them. .NET provides a way to both active and passive release unmanaged resources, that the Dispose method and type of their own Finalize method IDisposable interface. With any type of unmanaged resources, there is need to implement the Dispose method of IDisposable, and after you are finished using these types of objects need to call the Dispose method to manually release the object in unmanaged resources.

If the type correctly implement the Finalize method, even if not call the Dispose method, unmanaged resources will eventually be released, but then the resource has been occupied for a long time fearlessly.

The role of using statement is to provide an efficient way to call the Dispose method objects. For any type IDisposable interface, you can use the using statement, and those who do not implement the IDisposable interface type, use the using statement causes a compilation error.

A first look at using the basic syntax of the statement:

using(StreamWriter sw= new StreamWriter())
{
    // intermediate processing logic 
}

In the above code, using a start statement defines an object of StreamWriter, then sw can be used throughout the block of statements, the statements when using the end of the block, the Dispose method sw will be automatically invoked. using statements not only eliminates the programmers enter the code calls Dispose, it also provides a mechanism to ensure that the Dispose method is called, regardless of the end of a block of statements using smooth implementation, or throws an exception. The following code demonstrates using this protection mechanism.

using System;

namespace usingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 使用using
                using (MyDispose md = new MyDispose())
                {
                    md.DoWork();
                    // throw an exception to test a using 
                    the throw  new new Exception ( " throwing an exception " );
                }
            }
            catch
            {

            }
            finally
            {
                Console.ReadKey();
            }
        }
    }

    ///  <the Summary> 
    /// inherited from IDisposable interface, just to do the test, do not use any unmanaged resources
     ///  </ the Summary> 
    public  class MyDispose: IDisposable
    {
        public  void Dispose ()
        {
            Console.WriteLine ( " the Dispose method is called " );
        }
        public void DoWork()
        {
            Console.WriteLine ( " done a lot of work " );
        }
    }
}

In the above code, using statement block throws an exception, and the exception is caught to know before the end of the using statement. Thanks to the presence of using statements, even if an exception is thrown, DIspose method MyDispose objects md still be called. . Program output results are as follows:

In fact, C # compiler using statement is added automatically try / finally block, it is possible to ensure that the Dispose method to be invoked, so the following two codes of compiled content exactly:

using (MyDispose md = new MyDispose())
{
      md.DoWork();
}

with

MyDispose md;
try
{
    md = new MyDispose();
    md.DoWork();
}
finally
{
    md.Dispose();
}

In a thorough understanding of the implementation of the principle of using the later should also note that often make the wrong using, that is, do not attempt to initialize the object using statement outside the block, as shown in the code below:

MyDispose md = new MyDispose();
using (md)
{
    md.DoWork();
}

Seemingly without any problems, but in a multithreaded program, the above code will be hidden. Just when md after initialization procedure abruptly interrupted by an exception, then md object unmanaged resources will not have the opportunity to be released, which is harmful for the system is quite large. So at all times should be initialized using statements requires the use of objects.

Second, summary

using statement for the type of object implements IDisposable Dispose method call, using the statement to ensure that objects used by the Dispose method is called at the end using a block of statements, regardless of whether an exception is thrown. C # compiler at compile time automatically add the try / finally block using statements, and abnormal capture the essence of using the same sentence, but the syntax is more concise. All objects using use should start in using the statement after initialization, to ensure that all objects can be Dispose.

Guess you like

Origin www.cnblogs.com/dotnet261010/p/12329706.html