views:

53

answers:

2

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 cancellation 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

      }

    }
+1  A: 

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

SLaks
+1  A: 

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...

Hans Passant
so I was going to aggregate packet responses into 1 second summaries, only calculate a summary figure for the 1 second period, and then once per second feed this back to the UI. I thought that offloading this aggregation to a backgroundworker from the UI thread would be a good thing to do
Greg
Sounds okay. Use GetNextPacket with the timeout, the event will be raised on the wrong thread. Getting the 1 second intervals will be a wee bit tricky.
Hans Passant
actually it is http://pcapdotnet.codeplex.com/ library (not sharppcap) in fact sorry
Greg
Sigh. Well, use Sharppcap.
Hans Passant
actually (seriously) is there a real reason you would recommend Sharppcap? I found that with pcap.net I could get access down to the IP / TCP packet properties more easily and via intelisense than with SharpPcap. I'm still not sure which is the most solid or most used.
Greg