関数のプロセスを簡単に中断できない場合は、タイマーを使用して現在のスレッドを中止する必要がある場合があります (別のスレッドで関数を実行することを回避できます)。現在のスレッドが中止されるとすぐに、この中止を 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();
}
}