同步等待而不阻止UI线程

时间:2022-06-10 02:32:24

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

是否有一个同步等待函数不会占用.NET WPF中的UI线程?就像是:

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

2 个解决方案

#1


15  

You can use a DispatcherTimer for that sort of thing.

您可以使用DispatcherTimer进行此类操作。

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.)

(Dispatcher.PushFrame文档。)


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.

从.NET 4.5开始,您可以使用异步事件处理程序和Task.Delay来获得相同的行为。在这样的处理程序中简单地让UI更新返回Dispatcher.Yield。

#2


0  

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

这是Task.Delay的解决方案。我在使用DispatcherTimer的ViewModel的单元测试中使用它。

var frame = new DispatcherFrame();

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

Dispatcher.PushFrame(frame);

t.Wait();

#1


15  

You can use a DispatcherTimer for that sort of thing.

您可以使用DispatcherTimer进行此类操作。

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.)

(Dispatcher.PushFrame文档。)


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.

从.NET 4.5开始,您可以使用异步事件处理程序和Task.Delay来获得相同的行为。在这样的处理程序中简单地让UI更新返回Dispatcher.Yield。

#2


0  

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

这是Task.Delay的解决方案。我在使用DispatcherTimer的ViewModel的单元测试中使用它。

var frame = new DispatcherFrame();

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

Dispatcher.PushFrame(frame);

t.Wait();