Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I abort a .NET task?

Here's the situation, I am writing the framework for a code war contest. As the code runs, for each turn, it calls a method in the library provided by each contestant. The rules of the contest is the method must return in 1 second or we kill the task calling them. We then use a default result for that turn.

The method has no support for a cancel because we cannot trust the called code to respond to a cancel. And we need to kill the thread because if we have 10 or 20 ignored background tasks then all calls going forward will provide fewer clock cycles on each call and methods that before took less than 1 second now take more.

On the plus side, the method we're killing should have no resources open, etc. so an abort should not leave anything hanging.

Update: Two things to keep in mind here. First, this is like a game - so performance is important. Second, the worker thread is unlikely to have any resources open. If one of the called methods goes overlong, I need to abort it and move on quickly.

like image 472
David Thielen Avatar asked Aug 13 '11 20:08

David Thielen


2 Answers

You should run each contestant in his own AppDomain with low privileges. This has several advantages:

  1. It's sandboxed
  2. It can't interact with any other code in the process
  3. Force unloading an AppDomain is relatively clean.

Even if you prefer killing the thread over unloading the AppDomain I'd still put each contestant into an AppDomain to get the isolation.

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

like image 96
CodesInChaos Avatar answered Oct 26 '22 12:10

CodesInChaos


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

For communication, you should probably avoid .NET remoting, as that seems likely to be left in an inconsistent state on the server side. Some other choices: sockets, named pipes, web service.

like image 20
Dark Falcon Avatar answered Oct 26 '22 11:10

Dark Falcon