所有繼承 CWorkerThread 的類別必須實作五個抽象方法:
OnStart / OnStop:取得/釋放處理資源(如佇列連線、資料庫連線)。OnPause / OnContinue:暫時釋放/重新取得資源。ProcessMessage:核心訊息處理邏輯,失敗時拋出 CWorkerThreadException。建構子需呼叫基類建構子:
public CWorkerThreadDerived(CWorker parent, WorkerThreadFormatter formatter)
: base(parent, formatter) {}
配置檔提供輸出佇列路徑清單。OnStart 開啟所有佇列:
iQueues = wfThread.OutputName.Length;
mqOutput = new MessageQueue[iQueues];
for (int idx = 0; idx < iQueues; idx++) {
mqOutput[idx] = new MessageQueue(wfThread.OutputName[idx]);
mqOutput[idx].Formatter = new ActiveXMessageFormatter();
}
ProcessMessage 採循環分發:
try {
mqOutput[iNextQueue].Send(v_mInput);
} catch (Exception ex) {
throw new CWorkerThreadException(ex.Message, true); // 終止型異常
}
iNextQueue = (iNextQueue + 1) % iQueues;
配置檔指定組件路徑與類別名稱。OnStart 透過反射建立實例:
sFilePath = wfThread.OutputName[0]; // 組件 DLL 路徑
sTypeName = wfThread.OutputName[1]; // 完整類別名稱
Assembly asm = Assembly.LoadFrom(sFilePath);
Type typ = asm.GetType(sTypeName);
object obj = Activator.CreateInstance(typ);
iwmSample = (IWebMessage)obj; // 轉為介面
ProcessMessage 呼叫介面方法:
WebMessageReturn wbr;
try {
string label = v_mInput.Label;
string body = (string)v_mInput.Body;
int appSpec = v_mInput.AppSpecific;
wbr = iwmSample.Process(label, body, appSpec);
} catch (InvalidCastException ex) {
throw new CWorkerThreadException(ex.Message, false); // 非終止型
} catch (Exception ex) {
throw new CWorkerThreadException(ex.Message, true); // 終止型
}
switch (wbr) {
case WebMessageReturn.ReturnBad:
throw new CWorkerThreadException("Message marked bad", false);
case WebMessageReturn.ReturnAbort:
throw new CWorkerThreadException("Process terminating", true);
default: break;
}
範例組件將訊息寫入資料庫,嚴重錯誤標記為 Bad 而非終止服務。OnPause/OnContinue 釋放/重建組件參考,管理昂貴資料庫連線資源。