开发者

how to check for BackgroundWorker.CancellationPending when my thread has called another?

How should I check for a CancellationPending within a BackgroundWorker DoWork method, when within this method I call off to a Pcap.Net packet capture routine, which responses via a callback. The two options I can think of is:

a) write a loop at the bottom of the DoWork method to continually check for CancellationPending

b) put the check in the callback method I wrote which Pcap.Net will call back into - but no doubt the potential issue here is the cancellatio开发者_高级运维n can't work then until another patch match occurs and there is a callback

suggestions?

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

      }

    }


You don't need a BGW if you use the OnPacketArrival event. Makes it easy to stop, just call StopCapture().

The other way, GetNextPacket() does need a BGW. You have to open the device with a read timeout that short enough so you can see the CancellationPending flag quick enough. You'll also have to deal with the overhead of getting it displayed on your UI, ReportProgress is not cheap. And freezes the UI when you call it more often than ~1000 times per second.

I wonder if we're talking about the same library...


There is nothing wrong with delaying the cancellation until the next patch match; this is how BackgroundWorkers are supposed to work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜