public class ActionCall
{
/*例子
* static void Main(string[] args)
{
//try the five second method with a 6 second timeout
CallWithTimeout(FiveSecondMethod, 6000);
//try the five second method with a 4 second timeout
//this will throw a timeout exception
CallWithTimeout(FiveSecondMethod, 4000);
}
static void FiveSecondMethod()
{
Thread.Sleep(5000);
}*/
/// <summary>
/// 超时时间内执行方法
/// </summary>
/// <typeparam name="P"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="action"></param>
/// <param name="p"></param>
/// <param name="isSuccess">返回是否超时</param>
/// <param name="millisecondsTimeout"></param>
/// <returns></returns>
public static R CallWithTimeout<P, R>(Func<P, R> action, P p, out bool isTimeout, int millisecondsTimeout = Timeout.Infinite)
{
Thread threadToKill = null;
R r = default(R);
Action wrappedAction = () =>
{
threadToKill = Thread.CurrentThread;
r=action(p);
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(millisecondsTimeout))
{
wrappedAction.EndInvoke(result);
isTimeout = false;
}
else
{
//threadToKill.Abort();
//throw new TimeoutException();
Action abortAction = delegate
{
threadToKill.Abort();
};
abortAction.BeginInvoke(null, null);
isTimeout = true;
}
return r;
}
}