您想等於JavaScript的setTimeout的方法等。當用戶提供更多輸入時,這可以被取消:
代碼取自here。
public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
{
System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
timer.Elapsed += (source, e) =>
{
method();
};
timer.AutoReset = false;
timer.Enabled = true;
timer.Start();
// Returns a stop handle which can be used for stopping
// the timer, if required
return timer as IDisposable;
}
然後你可以在你的鑰匙了處理程序使用此:
void EndpointBox_KeyUp(object sender, KeyEventArgs e)
{
IDisposable timeout = SetTimeout(() => TestHTTP200(endpointBox.Text), 750);
if (this.currentTimeout != null) {
this.currentTimeout.Dispose();
this.currentTimeout = timeout;
}
}
這是最基本的原則,至少,每次重新開始一個750毫秒超時的用戶類型做你的事,並取消任何待定的計時器。
更新:完整的代碼示例:
public partial class Form1 : Form
{
private IDisposable currentTimeout;
public Form1()
{
InitializeComponent();
}
private void EndpointBox_KeyUp(object sender, KeyEventArgs e)
{
IDisposable timeout = TimerHelper.SetTimeout(() => TestHTTP200(EndpointBox.Text), 750);
if (this.currentTimeout != null)
{
this.currentTimeout.Dispose();
this.currentTimeout = timeout;
}
}
private void TestHTTP200(string text)
{
//...
}
}
public class TimerHelper
{
public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
{
System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
timer.Elapsed += (source, e) =>
{
method();
};
timer.AutoReset = false;
timer.Enabled = true;
timer.Start();
// Returns a stop handle which can be used for stopping
// the timer, if required
return timer as IDisposable;
}
}
來源
2013-05-12 12:36:03
Bas
設置一個['Timer'](http://msdn.microsoft.com/en-AU/library /system.timers.timer(v=vs.110).aspx)放在'KeyUp'上,然後將事件處理程序Timer.Elapsed設置爲API。 – 2013-05-12 12:33:41
我認爲[rx](http://msdn.microsoft.com/zh-cn/data/gg577609.aspx)對此具有很好的功能 – 2013-05-12 12:49:48