zoukankan      html  css  js  c++  java
  • Implementing a timeout on a function,实现对一个方法执行时间进行限制

    4.0版

    public static T Execute<T>(Func<T> func, int timeout)
    {
    T result;
    TryExecute(func, timeout, out result);
    return result;
    }

    public static bool TryExecute<T>(Func<T> func, int timeout, out T result)
    {
    var t = default(T);
    var thread = new Thread(() => t = func());
    thread.Start();
    var completed = thread.Join(timeout);
    if (!completed) thread.Abort();
    result = t;
    return completed;
    }

    2.0版

    public delegate object ExecuteMethod(object parameter);
    public static object Execute(ExecuteMethod executeMethod, object parameter, int timeout)
    {
    object result;
    TryExecute(executeMethod, parameter, timeout, out result);
    return result;
    }

    public static bool TryExecute(ExecuteMethod executeMethod,object parameter, int timeout, out object result)
    {
    object r=null;
    var thread = new Thread(() => r = executeMethod(parameter));
    thread.Start();
    var completed = thread.Join(timeout);
    if (!completed) thread.Abort();
    result = r;
    return completed;
    }

    referer:

    http://stackoverflow.com/questions/1370811/implementing-a-timeout-on-a-function-returning-a-value
    http://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/



  • 相关阅读:
    函数 out 传值 分割
    函数
    特殊集合
    集合
    数组

    穷举
    循环
    mac 软件安装
    实用信息查询接口
  • 原文地址:https://www.cnblogs.com/yczz/p/2409571.html
Copyright © 2011-2022 走看看