超时后中止卡住的方法

时间:2017-09-27 10:34:29

标签: c# multithreading reflection abort

我们的程序正在从DLL执行未知方法。有时这些方法不会处理超时,也永远不会返回值。

因此,我们的Methodinfo.invoke(...)将永远停留在此行上。

有没有可行的方法来中止我们的方法? 我明白我应该运行这个方法asyncronious这没问题。

这里要求的是可视化的一些小例子:

 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.
    }

1 个答案:

答案 0 :(得分:3)

正如评论中所建议的那样,如果在dll中分配了类似文件句柄的内容,我会尝试不使用ThreadAbortException

但是你走了:

    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();
    }

你需要在代码中的某个地方处理ThreadAbortException(没试过)。这段代码只是一个例子!你需要注意同时发生超时和成功的情况。因此,Timer在执行时不会被处理掉 - 并且可能有更多的竞争条件需要处理。