首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 訊息佇列應用程式開發:CWorkerThread 衍生類與訊息處理模式(六)

     編輯:關於C語言

CWorkerThread 衍生類實作規範

所有繼承 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;

模式二:呼叫實作 IWebMessage 介面的組件

配置檔指定組件路徑與類別名稱。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 釋放/重建組件參考,管理昂貴資料庫連線資源。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved