Implementing a timeout on a function, 한 방법의 실행 시간을 제한합니다

3020 단어 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-valuehttp://kossovsky.net/index.php/2009/07/csharp-how-to-limit-method-execution-time/

좋은 웹페이지 즐겨찾기