0

I have an external library that my code calls that sometimes hangs forever (but only on production!). I put the part that hangs into a seperate thread so I could just kill it and try again if it times out using the following, but it appears to hang when calling abort:

var triesLeft = 5;
while (triesLeft > 0) 
{
    var mre = new ManualResetEvent(false);

    var t = new Thread(_ => {
                           MethodThatHangsForever10PercentOfTheTime();
                           mre.Set();
                     });
    t.start();

    if (mre.WaitOne(TimeSpan.FromMinutes(20)))
    {
          break; // Success!
    }
    triesLeft--;

    log("this prints once");
    t.abort();
    log("this never prints");
  }
}

Is it possible that the spawned thread causes the main thread to hang when calling abort on it?

anthonybell
  • 5,790
  • 7
  • 42
  • 60
  • 1
    Just don't use `Abort`. It's virtually always the wrong solution to any given problem. – Servy Feb 05 '14 at 18:46
  • @Servy - So, what is the recommended solution? – Taegost Feb 05 '14 at 18:47
  • Well, the ideal solution would be to use code that doesn't break itself 10% of the time. That's a pretty horrible position to put yourself in. Either pressure the library to fix its code, contact their support to see if you're simply using it improperly, or find a way to avoid using a broken library method that misbehaves like this. – Servy Feb 05 '14 at 18:50
  • Could you move your code into an IIS-hosted wcf-service? You could then get automatic recycling and every other failsafe solution IIS provides. – sisve Feb 05 '14 at 18:52
  • 3
    Working with buggy third party library, it is sometimes a good idea to move it to another process, and talk with it using some interprocess communication way, like WCF. When library function hangs, just kill and restart the process. – Alex F Feb 05 '14 at 18:55
  • You mean a process could restart another process? Wouldn't my process need the ability to start and stop services then? – anthonybell Feb 05 '14 at 19:02
  • You might have luck using Tasks, like this: http://stackoverflow.com/questions/4036198/does-task-waitint-stop-the-task-if-the-timeout-elapses-without-the-task-finish – John Gibb Feb 05 '14 at 19:26
  • @JohnGibb And how do you plan to stop the `Task` that you've started if the code it is running starts to hang? – Servy Feb 05 '14 at 19:28

1 Answers1

1

Per MSDN, there is no way to guarantee a thread will end if you call abort. I'm also semi-positive Abort() will block until the exception actually is raised. However, I could be mistaken.

I suggest you take a look at the documentation here. There might be something you can glean from this on handling threads.

However, as Servy said, you're probably better off not using Abort. I'm of the same opinion.

Adam Sears
  • 355
  • 4
  • 14