[转载]How to avoid using() mistake in C#?

转载自http://blog.csdn.net/mikechenhua/article/details/42568893

 

As we know that in C# using() is suggested to avoid resourceleak or other good purposes, but in some cases it may be not suitable to use it,let me describe some of such kind of scenarios:

 

Assume that we have one MainForm which is the main windows of our App, which has 3 buttons on the UI and there is one child form ChildForm, which has one close button on the UI:

 

Design MainForm.cs as following code:

 

public partial class MainForm : Form

{

    public MainForm()

    {

        InitializeComponent();

    }

 

    private void usingChildForm_Click(object sender, EventArgs e)

    {

        using (ChildForm myForm = new ChildForm())

        {

            myForm.Show();// Inthis case, the child form will be disposed immediately, the user will have nochance to click Close button on it.

        }

    }

 

    public static void SyncThreadMethod()

    {

        Thread.Sleep(10000);

        MessageBox.Show("I am in Sync thread method.");

    }

    private void syncThreadButton_Click(object sender, EventArgs e)

    {

        using (DispoableThread thrd1 = new DispoableThread(new ThreadStart(SyncThreadMethod)))

        {

            thrd1.Start();

            thrd1.Join();// Inthis case, using() will wait until Sync thread calling is completed, thendispose thrd1. So “I am in Sync thread method.” will befirst, then “I am in Thread Dispose().”

        }

    }

 

    private void asyncThreadButton_Click(object sender, EventArgs e)

    {

        using (DispoableThread thrd1 = new DispoableThread(new ThreadStart(SyncThreadMethod)))

        {

            thrd1.Start();// Inthis case, using will also dispose(abort) thrd1 immediately, so only “I am in Thread Dispose().” is showed.

        }

    }

}

 

public class DispoableThread : IDisposable

{

    Thread trd = null;

    public DispoableThread(ThreadStart ts)

    {

        trd = new Thread(ts);

    }

 

    public void Start()

    {

        trd.Start();

    }

 

    public void Join()

    {

        trd.Join();

    }

 

    public void Dispose()

    {

        trd.Abort();

        MessageBox.Show("I am in Thread Dispose().");

    }

}

 

ChildForm.cs has:

 

public partial class ChildForm : Form
{
    public ChildForm()
    {
        InitializeComponent();
    }
    private void closeButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

 

You will found only when button “Using Sync Thread”isclicked, the using() can work correctly as we expected. In the other 2 cases,the using() will dispose the object declared in its scope no matter if the tasksinside its brackets is done or not.

 

转载自http://blog.csdn.net/mikechenhua/article/details/42568893

[转载]How to avoid using() mistake in C#?

上一篇:MYSQL——having 和 where的区别


下一篇:PostgresSQL (二) 基础语法 CREATE, INSERT INTO, SELECT