我們接管了一些.NET 1.1 Windows服務代碼,該代碼產生線程從隊列中讀取消息(請參閱eBeate eGate JMS隊列,但這並不重要),並反過來產生線程以處理目標應用程序服務中的消息。我們不斷遇到令我們困惑不已的邏輯和設計決策。這裏是一個例子,在該消息(lsMessage)已經從隊列中檢索並準備處理對象構造函數可以返回null嗎?
if(lsMessage != null)
{
// Initialize a new thread class instance, pass in message
WorkerThread worker = new WorkerThread(lsMessage);
Process:
// Start a new thread to process the message
Thread targetWorker = new Thread(new ThreadStart(worker.ProcessMessage));
if(targetWorker != null)
{
targetWorker.Priority = ThreadPriority.Highest;
targetWorker.Name = "Worker " + queueKey.ToString();
targetWorker.Start();
// wait for worker thread to join back in specified period
bool isFinished = targetWorker.Join(SYNC_THREAD_TIMEOUT);
string message = worker.replyMsg;
if (!isFinished) // BF is timeout
{
targetWorker.Abort();
// [obscure developer name] 25/10/2004: calling Join() to wait for thread to terminate.
// for EAI listener threads problem, ensure no new thread is started
// before the old one ends
targetWorker.Join();
// prepare reply message
string errorMsg = string.Format("EAIMsg {0}: BF is timeout. Send sync message back to caller.", worker.messageKey);
log.Debug(errorMsg);
message = worker.GenErrorCode(message, errorMsg);
}
// Commit message
MQ.ReceiverCommit(queueKey, worker.messageKey, false);
// Send back the response to the caller
MQ.RespondSend(queueKey, message);
}
else
{
log.Debug(string.Format("Fail to start worker thread to process sync message. Thread returned is null. Sleep for {0} milliseconds.", LIMIT_RESOURCE_SLEEP));
Thread.Sleep(LIMIT_RESOURCE_SLEEP);
goto Process;
}
}
請忽略使用標籤和GOTO暫時的;這不是問題。我們的困惑是在實例化後檢查線程對象是否爲空。下面的else語句似乎表明之前的開發人員遇到過這種情況。當然,原來的開發者早已不在了。所以我們想知道,CLR是否可以在調用構造函數之後實例化一個對象並返回null?我們不瞭解這種可能性。
長得重構或代碼的改變對我的結果。也許構造線是其他的東西,比如`GetThread()`。 – usr 2016-12-12 23:11:36