CWorkerThread 為 CWorkerThreadAppSpecific、CWorkerThreadRoundRobin、CWorkerThreadAssembly 三種具體處理器的共同基類。將佇列通用操作(開啟/關閉、接收迴圈、錯誤佇列寫入)封裝於基類,子類專注業務邏輯差異。
// 啟動:開啟輸入/錯誤佇列,建立處理執行緒
MessageQueue mqInput = new MessageQueue(sInputQueue);
mqInput.MessageReadPropertyFilter.Body = true;
mqInput.MessageReadPropertyFilter.AppSpecific = true;
MessageQueue mqError = new MessageQueue(sErrorQueue);
mqInput.Formatter = mqError.Formatter = new ActiveXMessageFormatter();
procMessage = new Thread(new ThreadStart(ProcessMessages));
procMessage.Start();
// 停止:標記停止旗標,等待執行緒結束,關閉佇列
bRun = false;
procMessage.Join();
mqInput.Close(); mqError.Close();
// 暫停/繼續:簡單 Sleep 讓出 CPU
if (bPause) Thread.Sleep(500);
四大生命週期方法均呼叫對應抽象方法(OnStart/Stop/Pause/Continue),提供子類資源管理掛鉤。
Message mInput;
try {
mInput = mqInput.Receive(new TimeSpan(0,0,0,1)); // 1 秒逾時
} catch (MessageQueueException mqe) {
mInput = null;
if (mqe.ErrorCode != -1072824293) { // 非逾時錯誤
LogError("Error: " + mqe.Message);
throw mqe;
}
}
if (mInput != null) {
try {
ProcessMessage(mInput); // 抽象方法,子類實作
} catch (CWorkerThreadException ex) {
ProcessError(mInput, ex.Terminate);
} catch {
ProcessError(mInput, true); // 未知異常視為終止型
}
}
// ProcessError:將錯誤訊息寫入錯誤佇列,若為終止型異常則拋出終止執行緒
設計亮點:
Receive 1 秒逾時屬正常輪詢,不記錯誤。CWorkerThreadException 攜帶 Terminate 旗標,區分「訊息層級失敗(繼續處理下一條)」與「系統層級失敗(終止執行緒)」。