Aborting task that contains never-ending library method (no ability of checking cancellation requests)

Viewed 191

I use Pcap.Net for traffic monitoring, and I need it to receive packets until user requests cancellation. I create monitoring task this way (simplified):

var task1 = Task.Run(() => { communicator.ReceivePackets(0, PacketHandlerCallback); } /*, token*/);

Here 0 says execution of ReceivePackets never ends, PacketHandlerCallback is a method that will be executed for each received packet. ReceivePackets is synchronous and does not support cancellation. Generally in my question it could be any other endless synchronous method which code we cannot edit.

The question is how to stop this method execution?

  • Just passing cancellation token to the task doesn't help because we should also explicitly check if cancellation is requested, e. g. by calling token.throwIfCancellationRequested().

  • Passing token to callback method is not a solution too because this method will not be invoked until new packet is received but I'd like to stop my task immediately after cancellation.

  • Using BackgroundWorker causes the same question since we should check CancellationPending.

  • Creating task2 that periodically checks cancellation requests and then writing var task = Task.WhenAny(task1, task2) doesn't help since ReceivePackets will still be executing.

Should I use Thread.Abort() or maybe there is any other elegant solution?
There are similar questions about TPL on SO but I cannot find any simple and helpful answer.

3 Answers
Related