简体   繁体   中英

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. This base class exposes an abstract method "ProcessData" which does some processing on data and returns the processed data. The main program iterates over all the included dll's and calls everyone's "ProcessData" function. 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". 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. 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. It isn't doing what you expect it to do .

Related reading: Careful with that axe, part one: Should I specify a timeout?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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