-3

Everyone knows thread should exit gracefully, but now I have to kill a thread.

When there is a request comming, I start a thread as below

_thread = new Thread(ProcessTemplate);
_thread.Start();

In the ProcessTemplate method, it takes use of Google V8 to compile and run a javascript code sent from client-side.

The problem is, the javascript sent from client-side could be buggy and cause an infinite loop.

Hence, I count the time since the thread start and if the javasctript execution time exceeds 10 second, I kill the thread like

try
{
    _thread.Abort();
}
catch
{
}

It works but also affects the current thread which started the _thread. I receive "Thread was being aborted." exception from current thread.

how to avoid/ignore the exception?

Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97

3 Answers3

3

I receive "Thread was being aborted." exception from current thread.

You receive this exception in the background thread, not in the main thread that started it as the documentation explains:

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.

So inside this background thread you can handle this exception:

_thread = new Thread(() => 
{
    try
    {
        ProcessTemplate();
    }
    catch (ThreadAbortException ex)
    {
        // the thread was aborted, call ResetAbort to 
        // avoid rethrowing the exception
        Thread.ResetAbort();
    }
);

Probably you are seeing the main thread affected because in certain cases unhandled exceptions in background threads could bring the AppDomain down. So normally you should handle those exceptions.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

You can use a Task and pass it a CancellationToken

Link

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
0

I receive "Thread was being aborted." exception from current thread.

Because that's what happens when you call Thread.Abort:

When this method is invoked on a thread, the system throws a ThreadAbortException in the thread to abort it. ThreadAbortException is a special exception that can be caught by application code, but is re-thrown at the end of the catch block unless ResetAbort is called.

You should catch the ThreadAbortException in your background thread and make sure its handled.

I would suggest that instead of using the rather dangerous abort, use the new features of the Task Parallel Library that allow for cooperative cancellations:

var cts = new CancellationTokenSource();
var ct = cts.Token;
var javaScriptTask = await Task.Run(() => ProcessTemplate, cts.Token);

And inside ProcessTemplate, monitor that CancellationToken:

ct.ThrowIfCancellationRequest();

Or, if you really want full control when making blocking calls, you should spin a new process to run your tasks.

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321