我遇到了臭名昭着的消息「線程xxx已退出代碼爲0(0x0)」的問題。隨機消息「線程已退出,代碼爲0」在託管線程中
在我的代碼,我有一個名爲「裝載」一主類,與Windows窗體加載事件開始:
public class Load
{
public Load()
{
Device[] devices = GetDevices(); // Get an array of devices from an external source
for (int i = 0; i < devices.Length; i++)
{
DeviceDiagnosticCtrl deviceDiagnostic = new DeviceDiagnosticCtrl(devices[i].name);
}
}
}
在構造函數中,從外部源讀取每個通用設備,我初始化一個自定義一個運行的線程診斷類:
public class DeviceDiagnosticCtrl
{
private Thread diagnosticController;
private volatile bool diagnosticControllerIsRunning = false;
public DeviceDiagnosticCtrl(string _name)
{
// Thread initialization
this.diagnosticController = new Thread(new ThreadStart(this.CheckDiagnostic));
this.diagnosticController.Start();
this.diagnosticControllerIsRunning = true;
}
private void CheckDiagnostic()
{
while (this.diagnosticControllerIsRunning)
{
try
{
// Custom 'Poll' message class used to request diagnostic to specific device
Poll poll = new Poll();
// Generic Message result to diagnostic request
IGenericMessage genericResult;
// Use a custom driver to send diagnostic request
SendSyncMsgResult res = this.customDriver.SendSyncMessage(poll, out genericResult);
switch (res)
{
case SendSyncMessageResult.GOOD:
{
// Log result
}
break;
case SendSyncMessageResult.EXCEPTION:
{
// Log result
}
break;
}
Thread.Sleep(this.customDriver.PollScantime);
}
catch (Exception ex)
{
// Loggo exception
}
}
}
}
當運行在調試模式下,上面的代碼我總是讀從外部源8點的裝置,以及用於它們中的每我連續運行託管線程來檢索診斷。 我的問題是,我期望從上面的代碼中隨機選擇的一個或多個8個線程以代碼0退出,沒有任何例外。
我已經很多時間在調試模式下啓動/重新啓動代碼,並且幾乎每次都有一個線程退出。
我讀過某處(i.e. this SO question),它可能取決於垃圾收集器的操作,但我不太確定這是否是我的情況 - 以及如何防止它。
是否有人在上面發佈的示例代碼中看到奇怪/錯誤的東西?任何建議?
此刻你正在吞嚥發生的任何異常......是否有任何事情得到Loggo'd?注意:線程退出*本身*沒有問題... –
@MarcGravell我已經把所有內容放在「Try-Catch」中,以確保我不會錯過任何可能的錯誤,但我沒有記錄任何東西( 「Loggo」是我意大利原始代碼中的一個錯字...在catch中,我在數據庫中寫入日誌。我知道「線程退出本身沒有問題」,但我的問題是我不希望這些線程自己退出,至少直到條件while(this.diagnosticControllerIsRunning)變爲false。 – Spaceman
'while(this.diagnosticControllerIsRunning)'很可能會立即失敗,在這種情況下,線程會退出。開始線程並且然後設置'this.diagnosticControllerIsRunning = true;'是沒有用的。 - 你很可能已經太遲了 - 你的馬已經狂奔了。 –