(trascritto da Ben come commento)
basta usare System.Windows.Forms.Timer. Imposta il timer per 5 secondi e gestisci l'evento Tick. Quando l'evento spara, fai la cosa.
...e disabilita il timer (IsEnabled = false) prima di eseguire il tuo lavoro in oder per sopprimere un secondo.
The Tick evento possono essere eseguito su un altro thread che non può modificare la vostra interfaccia grafica, si può prendere questo:
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
private void StartAsyncTimedWork()
{
myTimer.Interval = 5000;
myTimer.Tick += new EventHandler(myTimer_Tick);
myTimer.Start();
}
private void myTimer_Tick(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
/* Not on UI thread, reenter there... */
this.BeginInvoke(new EventHandler(myTimer_Tick), sender, e);
}
else
{
lock (myTimer)
{
/* only work when this is no reentry while we are already working */
if (this.myTimer.Enabled)
{
this.myTimer.Stop();
this.doMyDelayedWork();
this.myTimer.Start(); /* optionally restart for periodic work */
}
}
}
}
Solo per completezza: con async/attendono, si può ritardare l'esecuzione qualcosa molto facile (un solo colpo, non ripetere l'invocazione):
private async Task delayedWork()
{
await Task.Delay(5000);
this.doMyDelayedWork();
}
//This could be a button click event handler or the like */
private void StartAsyncTimedWork()
{
Task ignoredAwaitableResult = this.delayedWork();
}
Per ulteriori informazioni, vedere "async e aspettare" in MSDN.
Basta usare 'System.Windows.Forms.Timer'. Imposta il timer per 5 secondi e gestisci l'evento 'Tick'. Quando l'evento spara, fai la cosa. – Ben
Stiamo aggiungendo una nuova funzionalità al C# 5 che rende molto più semplice questo tipo di operazione asincrona; se sei interessato ad ottenere un picco, inizia con questo post del blog: http://blogs.msdn.com/b/csharpfaq/archive/2011/04/13/async-ctp-sp1-refresh.aspx –
Way per andare a Microsoft! –