C#解決文件被占用資源,無法刪除或修改的方法
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>
/// 線程執(zhí)行的方法,telnet獲取數(shù)據(jù)
/// </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,"數(shù)據(jù)打印完成!\n文件位置:" + localPath + "\n是否進(jìn)入該目錄?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(localPath);
}
this.Close();
System.Threading.Thread.CurrentThread.Abort();//終止當(dāng)前線程
}
catch(Exception e)
{
MessageBox.Show(this,"打印數(shù)據(jù)失敗!","提示");
System.Threading.Thread.CurrentThread.Abort();//終止當(dāng)前線程
this.Close();
}
System.Threading.Thread.CurrentThread.Abort();//終止當(dāng)前線程
}
private void button1_Click(object sender, EventArgs e)
{
//System.Threading.Thread.CurrentThread.Abort();//終止當(dāng)前線程
if (parameterThread_t != null)
{
parameterThread_t.Interrupt();
parameterThread_t.Abort();
parameterThread_t.Join();
GC.Collect();
}
this.Close();
}
例子:在winform窗口在onshow事件中啟動一個線程執(zhí)行telnet程序。當(dāng)點(diǎn)擊中止按鈕(button1_Click)中止線程再繼續(xù)執(zhí)行,并且釋放當(dāng)前線程占用的文件資源。
關(guān)鍵:parameterThread_t.Abort();parameterThread_t.Join(); GC.Collect();意思是,把線程Abort()停止線程執(zhí)行,Join();線程掛起直到線程中止了,然后再GC回收資源。
以上就是C#解決文件被占用資源的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C# 如何使用OpcUaHelper讀寫OPC服務(wù)器
這篇文章給大家介紹C# 如何使用OpcUaHelper讀寫OPC服務(wù)器,本文通過圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2023-12-12C#使用CefSharp實(shí)現(xiàn)內(nèi)嵌網(wǎng)頁詳解
這篇文章主要介紹了C# WPF里怎么使用CefSharp嵌入一個網(wǎng)頁,并給出一個簡單示例演示C#和網(wǎng)頁(JS)的交互實(shí)現(xiàn),感興趣的小伙伴可以了解一下2023-04-04c#網(wǎng)絡(luò)喚醒功能實(shí)現(xiàn)
網(wǎng)絡(luò)喚醒實(shí)現(xiàn)了對網(wǎng)絡(luò)的集中管理,即在任何時刻,網(wǎng)管中心的IT管理人員可以經(jīng)由網(wǎng)絡(luò)遠(yuǎn)程喚醒一臺處于休眠或關(guān)機(jī)狀態(tài)的計算機(jī),下面使用c#實(shí)現(xiàn)網(wǎng)絡(luò)喚醒功能2014-01-01C#使用WebSocket實(shí)現(xiàn)聊天室功能
這篇文章主要為大家詳細(xì)介紹了C#使用WebSocket實(shí)現(xiàn)聊天室功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02