Synchronous wait without blocking the UI stream

Is there a synchronous wait function that will not bind the UI thread in .NET WPF? Something like:

Sub OnClick(sender As Object, e As MouseEventArgs) Handles button1.Click Wait(2000) 'Ui still processes other events here MessageBox.Show("Is has been 2 seconds since you clicked the button!") End Sub 
+7
source share
1 answer

You can use DispatcherTimer for this kind of thing.

Edit: It can do and ...

 private void Wait(double seconds) { var frame = new DispatcherFrame(); new Thread((ThreadStart)(() => { Thread.Sleep(TimeSpan.FromSeconds(seconds)); frame.Continue = false; })).Start(); Dispatcher.PushFrame(frame); } 

( Dispatcher.PushFrame documentation. )


Starting with .NET 4.5, you can use async event handlers and Task.Delay to get the same behavior. To simply update the UI during such a handler, return Dispatcher.Yield .

+15
source

All Articles