I've got a function in a 3rd party library that occasionally goes rogue and never returns. Something like so:
// This is 3rd party function so I can't make it take a cancellation token.
public void RogueFunction()
{
while (true)
{
_logger.LogInformation("sleeping...");
Thread.Sleep(100);
}
}
I'd like to wrap it in a task with a timeout which is easy enough to do with a 'task.Wait(mills)'. While this returns control to me after the timeout, it doesn't actually kill the task.
In the code below, the rogue function continues to log after the timeout.
[Fact]
public void Test()
{
var task = Task.Factory.StartNew(RogueFunction);
var complete = task.Wait(500);
if (!complete)
{
// how do I kill the task so that it quits logging?
Thread.Sleep(5000);
task.Dispose(); // Throws exception: A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).
}
}
How do I completely kill this task, so that I can retry it without ending up with a bunch of them running infinitely on my background thread pool.