How to abort a .NET task?

Here is the situation, I am writing a framework for a code war contest. As you run the code for each move, it calls the library method provided by each member. Competition rules are a method that should return in 1 second or we kill the task that causes them. Then we use the default result for this reversal.

The method does not support cancellation, because we cannot trust the called code to respond to cancellation. And we need to kill the thread, because if we have 10 or 20 ignored background tasks, then all the calls going forward will provide fewer clock cycles for each call and the methods that used to take less than 1 second now require more.

On the plus side, the method we are killing should not open resources, etc., so an interrupt should not leave anything hanging.

Update: There are two things to keep in mind here. Firstly, it looks like a game, so performance is important. Secondly, the workflow is unlikely to open any resources. If one of the called methods is out of bounds, I need to cancel it and go quickly.

+6
source share
3 answers

You must run each member in your AppDomain with low privileges. This has several advantages:

  • It's a sandbox
  • It cannot interact with any other code in the process.
  • Forced unloading of AppDomain is relatively clean.

Even if you prefer to kill the thread when unloading the AppDomain, I would put each member in the AppDomain to get isolation.

Unfortunately, Thread.Abort not enough. It still executes finally clauses, which can take as long as they want.

+2
source

I would recommend that you run the code in the second process and carefully define the interface to communicate with it, to ensure that it can handle not receiving a response. Most operating systems are designed to clean well enough after killing the process.

For communication, you should probably avoid .NET deletions, as this is likely to remain in an inconsistent state on the server side. Some other options: sockets, named pipes, web service.

+1
source

The Thread.Interrupt () method is perhaps what you are looking for.

As the MSDN documentation says: "If this thread is not currently blocked in the standby, sleep, or connection state, it will be interrupted when it starts to block."

This is not an interrupt, it causes a running thread to raise a ThreadInterruptedException when the thread enters the idle state.

Then you can use the timer in another thread with a timeout to check if the thread really does not want to terminate, if the thread refuses to shut down, for example, 30 seconds, you can interrupt it.

+1
source

Source: https://habr.com/ru/post/894990/


All Articles