代码之家  ›  专栏  ›  技术社区  ›  Anwar Chandra

将超时设置为操作

  •  40
  • Anwar Chandra  · 技术社区  · 15 年前

    我有对象 obj 是第三方组件,

    // this could take more than 30 seconds
    int result = obj.PerformInitTransaction(); 
    

    我不知道里面发生了什么。 我所知道的是,如果时间长了,它就失败了。

    如何设置此操作的超时机制,以便如果超过30秒,我就抛出 MoreThan30SecondsException ?

    10 回复  |  直到 6 年前
        1
  •  70
  •   Paolo Tedesco    9 年前

    using System.Threading;
    
    class Program {
        static void DoSomething() {
            try {
                // your call here...
                obj.PerformInitTransaction();         
            } catch (ThreadAbortException) {
                // cleanup code, if needed...
            }
        }
    
        public static void Main(params string[] args) {
    
            Thread t = new Thread(DoSomething);
            t.Start();
            if (!t.Join(TimeSpan.FromSeconds(30))) {
                t.Abort();
                throw new Exception("More than 30 secs.");
            }
        }
    }
    
        2
  •  11
  •   Colonel Panic    8 年前

    Task.Wait(TimeSpan)

    using System.Threading.Tasks;
    
    var task = Task.Run(() => obj.PerformInitTransaction());
    if (task.Wait(TimeSpan.FromSeconds(30)))
        return task.Result;
    else
        throw new Exception("Timed out");
    
        3
  •  6
  •   Chris S    15 年前

    System.Threading.Timer

    private Thread _thread;
    
    void Main(string[] args)
    {
        _thread = new ThreadStart(ThreadEntry);
        _thread.Start();
        Timer timer = new Timer(Timeout,null,30000,Timeout.Infinite);
    }
    
    
    void ThreadEntry()
    {
        int result = obj.PerformInitTransaction(); 
    }
    
    void TimeOut(object state)
    {
        // Abort the thread - see the comments
        _thread.Abort();
    
        throw new ItTimedOutException();
    }
    

    Shutting Down Worker Threads Gracefully

    PerformInitTransaction() PerformInitTransaction ThreadAbortException

        4
  •  2
  •   Sean    15 年前

        5
  •  1
  •   Kangkan    15 年前

        6
  •  0
  •   Community CDub    7 年前
        7
  •  0
  •   Mike    7 年前

    public class Toolz {
        public static System.Threading.Tasks.Task<object> SetTimeout(Func<object> func, int secs) {
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(secs));
            return System.Threading.Tasks.Task.Run(() => func());
        }
    }
    
    class Program {
        static void Main(string[] args) {
            Console.WriteLine(DateTime.Now);
            Toolz.SetTimeout(() => {
                Console.WriteLine(DateTime.Now);
                return "";
            }, 10);
        }
    
    }
    
        8
  •  0
  •   Gilad Rave    7 年前

    public static bool DoWithTimeout(Action action, int timeout)
    {
        Exception ex = null;
        CancellationTokenSource cts = new CancellationTokenSource();
        Task task = Task.Run(() =>
        {
            try
            {
                using (cts.Token.Register(Thread.CurrentThread.Abort))
                {
                    action();
                }
            }
            catch (Exception e)
            {
                if (!(e is ThreadAbortException))
                    ex = e;
            }
        }, cts.Token);
        bool done = task.Wait(timeout);
        if (ex != null)
            throw ex;
        if (!done)
            cts.Cancel();
        return done;
    }
    

    public static bool DoWithTimeout<T>(Func<T> func, int timeout, out T result)
    {
        Exception ex = null;
        result = default(T);
        T res = default(T);
        CancellationTokenSource cts = new CancellationTokenSource();
        Task task = Task.Run(() =>
        {
            try
            {
                using (cts.Token.Register(Thread.CurrentThread.Abort))
                {
                    res = func();
                }
            }
            catch (Exception e)
            {
                if (!(e is ThreadAbortException))
                    ex = e;
            }
        }, cts.Token);
        bool done = task.Wait(timeout);
        if (ex != null)
            throw ex;
        if (done)
            result = res;
        else
            cts.Cancel();
        return done;
    }
    
        9
  •  0
  •   Ariful Islam    6 年前

        using System.Threading.Tasks;
    
        var timeToWait = 30000; //ms
        Task.Run(async () =>
        {
            await Task.Delay(timeToWait);
            //do your timed task i.e. --
            int result = obj.PerformInitTransaction(); 
        });
    
        10
  •  0
  •   user875234    6 年前

    Task.Run Task.Delay

    int sleepTime = 10000;
    Action myAction = () => {
        // my awesome cross-thread update code    
        this.BackColor = Color.Red;
    };
    new System.Threading.Thread(() => { System.Threading.Thread.Sleep(sleepTime); if (InvokeRequired) myAction(); else myAction(); }).Start();