开发者

Synchronous Wait Without Blocking the UI-Thread

开发者 https://www.devze.com 2023-03-07 23:51 出处:网络
Is there a synchronous wait function that won\'t tie up the UI-thread in .NET WPF?Something like: Sub OnClick(sender As Object, e As MouseEventArgs) Handles button1.Click

Is there a synchronous wait function that won't tie up the UI-thread in .NET WPF? Something like:

Sub OnClick(sender As Object, e As MouseEventArgs) Handles button1.Click
     Wait(2000) 
     'Ui still proc开发者_开发问答esses other events here
     MessageBox.Show("Is has been 2 seconds since you clicked the button!")
End Sub


You can use a DispatcherTimer for that sort of thing.

Edit: This might do as well...

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 behaviour. To simply let the UI update during such a handler return Dispatcher.Yield.


Here is a solution with Task.Delay. I'm using it in unit-tests for ViewModels that use DispatcherTimer.

var frame = new DispatcherFrame();

var t = Task.Run(
    async () => {
        await Task.Delay(TimeSpan.FromSeconds(1.5));
        frame.Continue = false;
    });

Dispatcher.PushFrame(frame);

t.Wait();
0

精彩评论

暂无评论...
验证码 换一张
取 消