简体   繁体   English

强制执行未知工作的线程在设置的时间后停止

[英]Force a thread which does unknown work to stop after a set amount of time

I have a "Module" abstract base class which users inherit from to create dll's for a particular program. 我有一个“模块”抽象基类,用户可以从中继承该基类来为特定程序创建dll。 This base class exposes an abstract method "ProcessData" which does some processing on data and returns the processed data. 该基类公开了抽象方法“ ProcessData”,该方法对数据进行一些处理并返回处理后的数据。 The main program iterates over all the included dll's and calls everyone's "ProcessData" function. 主程序遍历所有包含的dll,并调用每个人的“ ProcessData”函数。 Kind of like this: 有点像这样:

foreach (Module module in allModules)
{
   Data newData = module.ProcessData(oldData);
   //Do stuff with newData
}

There's a general "contract" that dll creators should abide by, which is that no file IO, web access, etc. should be performed in "ProcessData". dll创建者应遵守一个一般的“合同”,即“ ProcessData”中不应执行任何文件IO,Web访问等。 However, some of these user modules have bugs which occur every once in a while in which they enter an infinite loop (or so I assume). 但是,其中一些用户模块的错误有时会不时发生,它们会进入无限循环(或者我认为是这样)。

If I don't know what the heck these users are doing in their functions, is there still a way to halt their function execution if it's taking too long? 如果我不知道这些用户在他们的函数中到底干什么,如果花费的时间太长,还有办法停止他们的函数执行吗? I'd like my program to be robust enough to halt a module's execution if it detects that it's taking far too long, since right now the process thread just gets stuck forever. 我希望我的程序足够健壮,可以在检测到模块花费太长时间的情况下停止执行,因为现在进程线程永远被卡住了。 I've heard that starting a thread and then attempting "Abort" doesn't always work due to exception handling (among other things), but if I'm not in charge of the function, there must be some way for me to force it to stop. 我听说由于异常处理(除其他事项外),启动线程然后尝试“中止”并不总是有效,但是如果我不负责该功能,则必须有某种方法可以强制执行它停止了。 Hopefully.... 希望....

You have several options ordered by reliability and robustness in that order. 您有几个选项按可靠性和健壮性排序。

Recommended way is you could create separate process and execute the hostile code there. 推荐的方法是您可以创建单独的进程并在其中执行恶意代码。 Doing so will give you a chance to kill the process anytime you want. 这样做将使您有机会随时终止进程。

You could create separate AppDomain and run the code in that new AppDomain, and you can choose to unload the AppDomain anytime you want. 您可以创建单独的AppDomain并在该新AppDomain中运行代码,并且可以选择随时卸载AppDomain。 This is not robust as first option. 作为首选,这并不可靠。 But there is one. 但是有一个。

You might be tempted to just call Thread.Abort but don't do that. 您可能会想只调用Thread.Abort但不要这样做。 It isn't doing what you expect it to do . 它没有按照您的期望去做

Related reading: Careful with that axe, part one: Should I specify a timeout? 相关阅读: 小心那个斧头,第一部分:我应该指定超时时间吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM