同步等待而不会阻塞UI线程

问题描述

| 是否有一个同步等待功能不会占用.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
    

解决方法

可以将ѭ1用作此类事物。 编辑:这可能也做...
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
文档。) 从.NET 4.5开始,您可以使用
async
事件处理程序和
Task.Delay
获得相同的行为。简单地让用户界面在这样的处理程序中更新就返回“ 6”。     ,这是with5的解决方案。我正在单元测试中为使用
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();
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...