如果你不能轻易中断你的函数进程,你可能不得不使用定时器来中止当前线程(它避免你在另一个线程中执行你的函数)。一旦当前线程被中止,您可以使用 Thread.ResetAbort() 重新设置此中止,然后您可以执行程序的其他步骤。
所以你可以使用一个类似于这个的类
using System.Threading;
using System.Timers;
namespace tools
{
public class ThreadAbortTimer
{
public ThreadAbortTimer(int timeout)
{
_CurrentThread = Thread.CurrentThread;
_Timer = new System.Timers.Timer();
_Timer.Elapsed += _Timer_Elapsed;
_Timer.Interval = timeout;
_Timer.Enable = true;
}
/// <summary>
/// catch the timeout : if the current thread is still valid, it is aborted
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void _Timer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (typeof(ThreadAbortTimer))
{
if (_CurrentThread != null)
{
_CurrentThread.Abort();
_CurrentThread = null;
}
}
}
/// <summary>
/// timer that will check if the process lasts less than 30 seconds
/// </summary>
private readonly System.Timers.Timer _Timer;
/// <summary>
/// current thread to abort if the process is longer than 30 sec
/// </summary>
private Thread _CurrentThread;
/// <summary>
/// stop the timer
/// </summary>
public void Disable()
{
lock (typeof(ThreadAbortTimer))
{
_Timer.Enabled = false;
_CurrentThread = null;
}
}
/// <summary>
/// dispose the timer
/// </summary>
public void Dispose()
{
_Timer.Dispose();
}
}
}
然后你可以像这样使用它:
using (var timer = new ThreadAbortTimer(timeout))
{
try
{
// the process you want to timeout
}
catch
{
timer.Disable();
Thread.ResetAbort();
}
}