Question

I have a log-on process from an API I don't own that occasionally hangs. If it takes longer than, say, 30 seconds, I would like to kill it and retry (as it should take only about 2-3).

I'm a little confused about how aborting threads works, and whether or not I need to join after abortion. Here's my questions followed by an example of what I'm trying to do:

Questions:

  1. Abort throws a thread abortion exception in the thread its called on. Does that propagate? Do I need to explicitly handle in the calling thread it or does the thread just die?

  2. Do I need to join an aborted thread so it doesn't zombify, or am I just confused from the *NIX world of programming?

    public static Session GetSession()
    {
        Session session = new Session("user", "pass");
    
        try
        {
            //Create a thread to get the session so we can kill it if it hangs.
            Thread thread = new Thread(() => session.Logon());
    
            //Create a thread to kill the session thread if it hangs.
            Thread watcher = new Thread(() => HangKill(thread));
    
            //Start both threads.
            thread.Start();
            watcher.Start();
    
            //Wait for session thread to finish - abort kill thread if it does.
            thread.Join();
            watcher.Abort();
            watcher.Join();
        }
        catch (Exception ex)
        {            
            status = ex.ToString();
        }
    
        return session;
    }
    
    
    public static void HangKill(Thread t)
    {
        Thread.Sleep(30);
    
        if (t.IsAlive == true)
        {
            t.Abort();
        }
    }
    
Was it helpful?

Solution

Aborting threads in your own process is dangerous. (As well as in other processes, though.) The thread may own some locks, may be in the process of updating critical structures etc etc. So this is not the way to go.

I would suggest including the service in question into another process, so you can kill that process if something is going wrong. Use IPC (shared memory? WCF?) for communication with that process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top