应该释放线程对象? C#

时间:2012-04-04 08:42:22

标签: wpf c#-4.0

public partial class MainWindow : window
{
    private Thread t = new Thread;

    private void btnSend_Click(object sender, RoutedEventArgs e)
    {
        if (t != null)
        {
            if (t.IsAlive == true)
            {
                t.Abort();
                t = null; //Is this correct? should I free this before making null?
                return;
            }

            t = new Thread(send.Image);
            t.Start();    
        }
    }
}

上面的代码显示了一个事件处理程序。当我按下一个名为“发送”的按钮时,应该创建新进程。当我点击相同的按钮时,进程应该停止。然后,我将再次按“发送”,然后该过程应重新开始。线程应该在同一个对象't'中创建。

2 个答案:

答案 0 :(得分:1)

取消引用Thread的好处是,您允许GC收集Thread类所持有的任何数据,但是当您调用Abort时,您将永久stop the thread。由于线程类没有实现IDisposable,因此无法确定性地释放该类持有的任何非托管资源,我们希望Abort能够做到这一点。

Thread类的重量相当轻,除非你有许多MainWindows同时运行,否则它可能不会影响你的内存消耗。但是,如果你知道你再也不会使用它们,那么最好去掉你的对象。

答案 1 :(得分:1)

技术上可以这样做,但你必须这样做:

private Thread t; // initially null
private void btnSend_Click(object sender, RoutedEventArgs e) 
{ 
    if (t != null) 
    { 
        t.Abort(); 
        t = null;
    }
    else
    {
        t = new Thread(send.Image); 
        t.Start();     
    } 
} 

此外,调用Abort可能不是一个好的设计。

您可能会以循环检查WaitHandle的方式实现您的线程方法。这使线程能够以受控方式终止:

private Thread t; // initially null
private AutoResetEvent waitHandle = new AutoResetEvent(false);

private void btnSend_Click(object sender, RoutedEventArgs e) 
{ 
    if (t != null) 
    { 
        waitHandle.Set(); // signal thread termination
        t = null;
    }
    else
    {
        t = new Thread(ThreadMethod); 
        t.Start();     
    } 
} 

private void ThreadMethod()
{
    TimeSpan waitTime = TimeSpan.FromSeconds(1);
    while (!waitHandle.WaitOne(waitTime))
    {
        // do something
    }
}
相关问题