2011-01-19 85 views
1

我已經繼承了一個多線程Windows服務(C#,.NET),但不支持無端異常。該服務使用多個線程從遙測設備收集數據進行分析。此服務中的線程可以運行24小時或更長時間。我正在努力如何告訴主線程線程遇到問題並需要回收。下面是代碼的簡化視圖:線程:使用C#調用返回到.NET Windows服務的主線程

class Program 
{ 
    static void Main(string[] args) 
    { 
    var workerObject = new WorkerObject(); 
    var workerThread = new Thread(workerObject.DoWork); 
    workerThread.Start() 
    } 
} 

class WorkerObject 
{ 
    //todo: My fields and properties go here 

    public void DoWork() 
    { 
    const int timeout = 100; 

    //todo: setup wait handles here 

    try 
    { 
     //Start monitoring channels for this device 
     while (true) 
     { 
     // Wait on any waithandle or timeout once per decisecond. 
     int channelIndex = WaitHandle.WaitAny(waitHandles, timeout, false); 

     //todo: process incoming data for this channel 
     } 
    } 
    //Catch all exceptions so we can notify mommy that we're in a bad way 
    catch (Exception ex) 
    { 
     //todo: log anything that can help us figure this problem out 

     //How do I tell the main thread I've failed 
    } 
    finally 
    { 
     //But of course we want to clean up after ourselves 
    } 
    } 
} 

這是否甚至是最好的.NET線程機制?我應該使用Async Delegates還是Task Parallel Library?

回答

2

我最近有類似的要求。我不認爲你可以依靠子線程告訴父母,當他們是壞的。如果他們陷入無限循環或出於某種原因而陷入僵局會怎麼樣?我以「看門狗」的方式安頓下來。每個子線程都需要將「心跳線」發送回主線程。如果沒有收到這個信號,那麼線程被認爲是「死亡」並且可以採取行動。這是一個關於我落戶在體系結構上一篇:

http://blog.bobcravens.com/2009/08/monitored-watchdog-asynchronous-process-in-c/

希望這有助於。

鮑勃

+0

哥們你可以在你的代碼中添加一個鏈接到源代碼?不可能理解任何事情。 – IamStalker 2015-01-29 09:35:33

0

丹尼爾蛾在博客了很多關於多線程以及最近的並行任務支持.NET 4.0。這是一個很好的資源,http://www.danielmoth.com,非常有趣。我肯定會檢查出來的。

我不確定這是否有幫助,但我曾在一個「Report Runner」Windows服務中從一個隊列中獲取作業,然後計劃ThreadPool上的工作;這很好,因爲如果「報告」失敗,我只記錄錯誤並退出函數,因爲它是在ThreadPool中計劃的,它只會返回到池中以運行更多報告。如果你正在運行的代碼失敗,使用ThreadPool可以避免管理一個新線程所需的代碼。