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;
}
}
}