Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to kill a blocked thread?

I have a thread:

void threadCode(object o)
{
  doStuffHere(o); // Blocking call. Sometimes hangs.
}

and I'm calling it like this:

Thread t = new Thread(new ThreadStart(delegate()
  {
    threadCode(o);
  }));
t.Start();

StopWatch sw = new StopWatch();
sw.Start();

while (t.IsAlive)
{
  Application.DoEvents();

  if (sw.EllapsedMilliseconds > myTimeout)
    // Somehow kill t even though doStuffHere(o) is blocked (but hung)
}

I'm using the .NET Zip Library and calling ZipFile.CommitUpdate() which works most of the time, but sometimes just hangs. I don't know why, I can't see anything in the documentation which specifies why this is happening. A small file which should take no longer than 5 - 10 seconds will sometimes sit there for more then 5 minutes with no progress. I/O graphs in process explorer show that the process is not reading or writing, and there is no CPU usage. Basically, if this happens, I want to kill CommitUpdate() and try again once or twice before giving up.

Any idea how I can kill a thread stuck in a blocking call?

(Alternatively - those of you with experience with this zip library: do you know why it might be hanging with some files sometimes? I'm modifying the contents of .docx and .pptx (GZip) files. This would be an ideal solution.)

like image 422
Ozzah Avatar asked Dec 01 '22 03:12

Ozzah


1 Answers

If you're going to terminate the hanging thread by using Thread.Abort(), make sure you handle ThreadAbortException in your thread code. The normal pattern is:

try {
    // do work here
}
catch (ThreadAbortException) {
    // allows your thread to gracefully terminate
    Thread.ResetAbort();
}
catch {
    // regular exception handling
}

If you don't follow the above pattern, then at best your threads will terminate ungracefully. At worst, you could run into a number of other problems.

like image 175
Bradley Smith Avatar answered Dec 03 '22 17:12

Bradley Smith