如何?释放调用 类 的资源我的一个WinForm程序,调用了另外一个类Class的方法(循环),当我关闭WinForm程序时候报错。
调试了下,当我关闭WinForm应用程序时,Class中的那循环还在执行。我在WinForm中已经Dispose,Class中也已经Dispose了。在WinForm关闭时,请问如何彻底的释放资源,释放WinForm与Class的所有资源!!请教,谢谢!!!

解决方案 »

  1.   

    你是否使用了线程?
    在该类Dispose的时候应该释放属于该Class的所有资源
    显然你没有释放干净
    比如线程的停止~~~~
      

  2.   

    当我关闭WinForm应用程序时,Class中的那循环还在执行。我在WinForm中已经Dispose,Class中也已经Dispose了。应该是这个循环还没执行完,如:
    循环执行需10s,5s时,窗口就请求关闭;可以用线程来做,窗口就请求关闭时,强制关闭循环;还可以在循环未完成,不让关闭窗口
      

  3.   

    dispose()并不能帮你释放所有的资源,比如正在运行的循环,要重写dispose,然后可以用两种方法解决:
    0、如何重写dispose
            private System.ComponentModel.IContainer components = null;
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    1、全局标识符控制循环
    生命全局或其他方式的变量globalFlag
    while(true)
    {
    ...
    if(globalFlag)break;
    }
    在dispose()里写
    .....globalFlag = true;
    2、线程
    void mythread()
    {
    while(true)
    {
    ...
    }
    }
            //启动线程
            public void StartThread()
            {
                StopThread();
                timerThread = new Thread(new ThreadStart(mythread));
                //获取或设置一个值,该值指示某个线程是否为后台线程。
                timerThread.IsBackground = true;
                timerThread.Start();
            }        //停止线程
            public void StopThread()
            {
                if (timerThread != null)
                {
                    //中断线程
                    timerThread.Interrupt();
                    timerThread = null;
                }
            }
      

  4.   

    可以再加个ManualResetEvent,关闭的时候等待当前循环完毕,在关闭窗口.