方法执行超时则终止方法思路
今天想一个方法的超时则强行终止该方法思路,处于实验阶段,尚未正式使用。总体思路如下:
1,把需要执行的方法放在一个线程中A,执行。
2,把线程A作为参数传入线程B中,在B中执行一个循环,如果超时则强行终止该线程。
代码如下:
详细代码
public interface IExcecMehtod
{
void ExecMethodWithLongTime();
}
public class MethodExecHelper
{
#region 全局变量
IExcecMehtod methodHost = null;
public IExcecMehtod MethodHost
{
get { return methodHost; }
set { methodHost = value; }
}
private int timeOut;
/// <summary>
/// 方法执行超时时间(单位:秒)
/// </summary>
public int TimeOut
{
get
{
return timeOut;
}
set
{
timeOut = value;
}
}
#endregion
#region 构造函数
public MethodExecHelper(IExcecMehtod methodHost, int timeOut)
{
this.methodHost = methodHost;
this.timeOut = timeOut;
}
public MethodExecHelper(IExcecMehtod methodHost)
: this(methodHost, 5)
{
}
#endregion
#region 对外方法
public void Run()
{
Thread execThread = new Thread(new ThreadStart(WaitMethod));
execThread.Start();
Thread abortThread = new Thread(new ParameterizedThreadStart(AbortMehtod));
abortThread.Start(execThread);
}
#endregion
#region 私有方法
void AbortMehtod(object state)
{
bool flag = false;
DateTime beginTime = DateTime.Now;
while (!flag)
{
DateTime currentTime = DateTime.Now;
if ((currentTime - beginTime).Seconds > TimeOut)
{
Thread thread = state as Thread;
if (thread != null)
{
if (thread.IsAlive)
{
thread.Abort();
Debug.WriteLine("线程强行终止");
}
}
flag = true;
}
Thread.Sleep(1000);
}
}
void WaitMethod()
{
MethodHost.ExecMethodWithLongTime();
Debug.WriteLine("线程执行完成");
}
#endregion
}