Implement C# Generic Timeout

后端 未结 7 1716
谎友^
谎友^ 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:05

    Well, you could do things with delegates (BeginInvoke, with a callback setting a flag - and the original code waiting for that flag or timeout) - but the problem is that it is very hard to shut down the running code. For example, killing (or pausing) a thread is dangerous... so I don't think there is an easy way to do this robustly.

    I'll post this, but note it is not ideal - it doesn't stop the long-running task, and it doesn't clean up properly on failure.

        static void Main()
        {
            DoWork(OK, 5000);
            DoWork(Nasty, 5000);
        }
        static void OK()
        {
            Thread.Sleep(1000);
        }
        static void Nasty()
        {
            Thread.Sleep(10000);
        }
        static void DoWork(Action action, int timeout)
        {
            ManualResetEvent evt = new ManualResetEvent(false);
            AsyncCallback cb = delegate {evt.Set();};
            IAsyncResult result = action.BeginInvoke(cb, null);
            if (evt.WaitOne(timeout))
            {
                action.EndInvoke(result);
            }
            else
            {
                throw new TimeoutException();
            }
        }
        static T DoWork(Func func, int timeout)
        {
            ManualResetEvent evt = new ManualResetEvent(false);
            AsyncCallback cb = delegate { evt.Set(); };
            IAsyncResult result = func.BeginInvoke(cb, null);
            if (evt.WaitOne(timeout))
            {
                return func.EndInvoke(result);
            }
            else
            {
                throw new TimeoutException();
            }
        }
    

提交回复
热议问题