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/



你可能感兴趣的:(function)