Implement C# Generic Timeout

后端 未结 7 1732
谎友^
谎友^ 2020-11-22 09:39

I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.

TemperamentalClass t         


        
7条回答
  •  情话喂你
    2020-11-22 10:26

    What about using Thread.Join(int timeout)?

    public static void CallWithTimeout(Action act, int millisecondsTimeout)
    {
        var thread = new Thread(new ThreadStart(act));
        thread.Start();
        if (!thread.Join(millisecondsTimeout))
            throw new Exception("Timed out");
    }
    

提交回复
热议问题