1

Our C# code calls a library to initialize a hardware device, and in some circumstances that call can block if the hardware fails to respond. In order that our code times out, I considered calling the library function in a task that and using a wait with a timeout on a ManualResetEvent. If the wait returns false, the device did not initialize. But that still leaves the task running (blocked). Since I can't pass cancellation tokens into the library code, how then can I abort the task?

public class Foo
{
    ManualResetEvent _event = new ManualResetEvent( false );
    Device _device = new Device();

    public bool Initialize()
    {
        _event.Reset();
        Task.StartNew( ()=>
        {
            if (_device.Initialize())
            {
                _event.Set();
            }
        } );
        if ( !_event.Wait( 10000 ) )
        {
            // Device did not initialize. Stop task?
            return false;
        }
        else
        {
            return true;
        }
    }
}
leppie
  • 115,091
  • 17
  • 196
  • 297
Julian Gold
  • 1,246
  • 2
  • 19
  • 40
  • possible duplicate of [How do I abort/cancel TPL Tasks?](http://stackoverflow.com/questions/4783865/how-do-i-abort-cancel-tpl-tasks) – usr Jul 04 '14 at 10:07
  • 1
    Your issue of cancelling a non-cancellable task is not new. The suggested duplicate is the same underlying issue. – usr Jul 04 '14 at 10:07

1 Answers1

0

There is no way to reliably cancel the particular task that you are running, you can pass in a CancellationToken but that requires the long running operation _device.Initialize() to support cancellation which it doesn't by the looks of it.

Still, there is a way to do it with Thread.Abort and CancellationTokenSource but that can leave the system and your device in an unstable state. Have a look at this question for how to do that.

Community
  • 1
  • 1
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61