如何使用超时包装流氓函数? [英] How do I wrap a rogue function with a timeout?
问题描述
我在 3rd 方库中有一个函数,该函数偶尔会出问题并且永远不会返回.像这样:
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);
}
}
我想将它包装在一个带有超时的任务中,这很容易用'task.Wait(mills)'来完成.虽然这会在超时后将控制权返回给我,但它实际上并没有终止任务.
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.
推荐答案
看来 Thread.Abort
是你唯一的选择.如果您担心这样做会使应用程序处于损坏状态(打开文件句柄等),那么最安全的选择是在不同的进程中运行线程,然后 终止进程.另一个可行的解决方案是在不同的 AppDomain 中运行线程,然后中止线程并 卸载应用域.
It seems that Thread.Abort
is your only option. If you are afraid that doing so may leave the application in a corrupted state (open file handles etc), then the safest option is to run the thread in a different process, and then kill the process. Another workable solution is to run the thread in a different AppDomain, and then abort the thread and unload the AppDomain.
这篇关于如何使用超时包装流氓函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!