Come inserire un ritardo prima di eseguire un'operazione in WPF

 C Programming >> Programmazione C >  >> Tags >> WPF
Come inserire un ritardo prima di eseguire un'operazione in WPF

La soluzione per Come ritardare prima di eseguire un'operazione in WPF
è riportata di seguito:

Ho provato a utilizzare il codice seguente per fare un ritardo di 2 secondi prima di passare alla finestra successiva. Ma il thread sta invocando per primo e il blocco di testo viene visualizzato per un microsecondo e atterrato nella pagina successiva. Ho sentito dire che l'avrebbe fatto un spedizioniere.

Ecco il mio frammento:

tbkLabel.Text = "two mins delay";
Thread.Sleep(2000);
Page2 _page2 = new Page2();
_page2.Show();

La chiamata a Thread.Sleep sta bloccando il thread dell'interfaccia utente. Devi attendere in modo asincrono.

Metodo 1:usa un DispatcherTimer

tbkLabel.Text = "two seconds delay";

var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Start();
timer.Tick += (sender, args) =>
    {
        timer.Stop();
        var page = new Page2();
        page.Show();
    };

Metodo 2:usa Task.Delay

tbkLabel.Text = "two seconds delay";

Task.Delay(2000).ContinueWith(_ => 
   { 
     var page = new Page2();
     page.Show();
   }
);

Metodo 3:nel modo .NET 4.5, usa async/await

// we need to add the async keyword to the method signature
public async void TheEnclosingMethod()
{
    tbkLabel.Text = "two seconds delay";

    await Task.Delay(2000);
    var page = new Page2();
    page.Show();
}