Implement C# Generic Timeout

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

    I just knocked this out now so it might need some improvement, but will do what you want. It is a simple console app, but demonstrates the principles needed.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    
    namespace TemporalThingy
    {
        class Program
        {
            static void Main(string[] args)
            {
                Action action = () => Thread.Sleep(10000);
                DoSomething(action, 5000);
                Console.ReadKey();
            }
    
            static void DoSomething(Action action, int timeout)
            {
                EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
                AsyncCallback callback = ar => waitHandle.Set();
                action.BeginInvoke(callback, null);
    
                if (!waitHandle.WaitOne(timeout))
                    throw new Exception("Failed to complete in the timeout specified.");
            }
        }
    
    }
    

提交回复
热议问题