zoukankan      html  css  js  c++  java
  • C# 给某个方法设定执行超时时间-2

     var response = RunTaskWithTimeout<ReturnType>(
            (Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
    
    
        /// <summary>
        /// Generic method to run a task on a background thread with a specific timeout, if the task fails,
        /// notifies a user
        /// </summary>
        /// <typeparam name="T">Return type of function</typeparam>
        /// <param name="TaskAction">Function delegate for task to perform</param>
        /// <param name="TimeoutSeconds">Time to allow before task times out</param>
        /// <returns></returns>
        private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
        {
            Task<T> backgroundTask;
    
            try
            {
                backgroundTask = Task.Factory.StartNew(TaskAction);
                backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
            }
            catch (AggregateException ex)
            {
                // task failed
                var failMessage = ex.Flatten().InnerException.Message);
                return default(T);
            }
            catch (Exception ex)
            {
                // task failed
                var failMessage = ex.Message;
                return default(T);
            }
    
            if (!backgroundTask.IsCompleted)
            {
                // task timed out
                return default(T);
            }
    
            // task succeeded
            return backgroundTask.Result;
        }

    https://stackoverflow.com/questions/13513650/how-to-set-timeout-for-a-line-of-c-sharp-code

  • 相关阅读:
    构造 非构造 代码块
    Random 类生成随机数
    JAVA寄存器
    PyCharm配置远程python解释器和在本地修改服务器代码
    Java实现常见的排序算法
    推荐系统冷启动问题解决方案
    AVL树C代码
    AVL树->图解2
    AVL树->图解1
    二叉查找树(Binary Sort Tree)
  • 原文地址:https://www.cnblogs.com/tianciliangen/p/7126442.html
Copyright © 2011-2022 走看看