首页 > 其他分享 >超时时间内执行方法 ActionCall.CallWithTimeout

超时时间内执行方法 ActionCall.CallWithTimeout

时间:2022-11-14 23:32:18浏览次数:42  
标签:null Thread ActionCall second threadToKill result CallWithTimeout FiveSecondMeth


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;
}

}



标签:null,Thread,ActionCall,second,threadToKill,result,CallWithTimeout,FiveSecondMeth
From: https://blog.51cto.com/u_688107/5851229

相关文章