现在的位置: 首页 > 综合 > 正文

C#解决文件被占用资源,无法删除或修改办法

2013年03月18日 ⁄ 综合 ⁄ 共 1354字 ⁄ 字号 评论关闭
        Thread parameterThread_t = null;
        private void Print_DetailForm_Shown(object sender, EventArgs e)
        {

            parameterThread_t = new Thread(new ParameterizedThreadStart(this.openThread_telnet));
            //parameterThread_t.IsBackground = false;
            parameterThread_t.Start(null);
        }

        /// <summary>
        /// 线程执行的方法,telnet获取数据
        /// </summary>
        private void openThread_telnet(Object obj)
        {
            //TelNet_Manage manage = new TelNet_Manage();
            try
            {
                manage.PrintBySockets(null, wy_name, table, progressBar1, label2);
                String localPath = Environment.CurrentDirectory + @"\Ne_data\wy\" + wy_name;
                if (MessageBox.Show(this,"数据打印完成!\n文件位置:" + localPath + "\n是否进入该目录?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(localPath);
                }
                this.Close();
                System.Threading.Thread.CurrentThread.Abort();//终止当前线程
            }
            catch(Exception e)
            {
                MessageBox.Show(this,"打印数据失败!","提示");
                System.Threading.Thread.CurrentThread.Abort();//终止当前线程  
                this.Close();
            }
            System.Threading.Thread.CurrentThread.Abort();//终止当前线程  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //System.Threading.Thread.CurrentThread.Abort();//终止当前线程
            if (parameterThread_t != null)
            {
                parameterThread_t.Interrupt();
                parameterThread_t.Abort();
                parameterThread_t.Join();
                
                GC.Collect();
            }
            this.Close();
        }

 

例子:在winform窗口在onshow事件中启动一个线程执行telnet程序。当点击中止按钮(button1_Click)中止线程再继续执行,并且释放当前线程占用的文件资源。

关键:parameterThread_t.Abort();parameterThread_t.Join(); GC.Collect();意思是,把线程Abort()停止线程执行,Join();线程挂起直到线程中止了,然后再GC回收资源。

抱歉!评论已关闭.