Search code examples
c#multithreadingreflectionabort

Aborting a stuck method after a timeout


Our program is executing unknown methods from a DLL. Sometimes those methods won't handle timeouts and will never return a value.

Thus, our Methodinfo.invoke(...) will be stuck on this line forever.

Is there any decent way to abort our method? I understand that i should probably run this method asyncronious which is no problem.

as requested here is some little example for visualisation:

 public string startTheDLLMethod(int timeout)
    {
        var methodinfo = "...";

        return methodGettingStuck(methodinfo); //todo, abort this after timeout
    }

    public string methodGettingStuck(methodinfo)
    {
        var1 = "";
        var2 = "";

        methodinfo.Invoke(var1, var2); //Stuck.
    }

Solution

  • As suggested in the comment i would try to not work with ThreadAbortException if something like a file handle is allocated within the dll.

    But here you go:

        public void BlockingCallWithTimeout()
        {
            Semaphore waitHandle = new Semaphore(0,1);
            Thread thread = new Thread(this.Wrapper);
            Timer timer = new Timer(state =>
            {
                thread.Abort();
                waitHandle.Release();
            },null,5000,0);
    
            thread.Start(waitHandle);
    
            waitHandle.WaitOne(); //wait until completion or until timeout
            timer.Dispose();
        }
    
        public void Wrapper(object state)
        {
            Semaphore semaphore = (Semaphore)state;
    
            //Call DLL Method
    
            semaphore.Release();
        }
    

    You need to handle the ThreadAbortException somewhere in the code (did not try it). This code is just an example! you need to take care of the case where timeout and success occur at the same time. So the Timer is not disposed the moment it is executing - and there may be more race conditions to take care of.