2010-07-21 29 views
0

我應該如何檢查BackgroundWorker DoWork方法中的CancellationPending,在此方法中,我將調用Pcap.Net數據包捕獲例程(通過回調進行響應)。我能想到的兩個選項是:如何檢查BackgroundWorker.CancellationPending當我的線程調用另一個?

一)在DoWork的方法的底部寫一個循環來不斷地檢查CancellationPending

二)把檢查的回調方法我寫了Pcap.Net會回撥 - 但毫無疑問,這裏的潛在問題是取消不能工作,直到另一個補丁匹配發生,並有回調

建議?

public class MainClass { 
     private void bgWorker_DoWork(object sender, DoWorkEventArgs e) 
     { 
      var worker = sender as BackgroundWorker; 
      _packetCapturer = new PacketCapturer(); 
     } 

} 

    public class PacketCapturer 

     public PacketCapturer() { 
     // Start Capture Here 
     // Opens PacketCommunicator 
     // communicator.ReceivePackets(0, PacketCapturerCallback); 

     } 

     private static void PacketCapturerCallback(Packet packet) { 
     // Deal with returned packet 

     } 

    } 

回答

1

如果您使用OnPacketArrival事件,則不需要BGW。停下來很簡單,只需調用StopCapture()即可。

另一種方式,GetNextPacket()確實需要一個BGW。您必須以足夠短的讀取超時打開設備,以便足夠快地看到CancellationPending標誌。您還必須處理在UI上顯示的開銷,ReportProgress是而不是便宜。當你每秒調用UI的次數大於1000次時會凍結UI。

我懷疑我們是否在談論同一個庫...

+0

所以我要彙總數據包響應到1秒總結,只計算1秒時間段的彙總數字,再一次每秒鐘將其反饋回UI。我認爲從UI線程卸載這個聚合到背景工作將是一件好事 – Greg 2010-07-21 03:25:25

+0

聽起來沒問題。使用GetNextPacket超時,事件將在錯誤的線程上引發。獲得1秒的間隔將會有點棘手。 – 2010-07-21 03:31:22

+0

其實它是http://pcapdotnet.codeplex.com/庫(不是sharppcap)其實對不起 – Greg 2010-07-21 03:49:16

1

延遲取消直到下一個補丁匹配沒有任何錯誤;這是BackgroundWorkers應該如何工作的。

相關問題