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回收資源。
以上就是C#解決文件被占用資源的全部內容,希望能給大家一個參考,也希望大家多多支持武林網。