在.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发布于 2011-05-25 05:46:29
你可以使用DispatcherTimer来做这类事情。
编辑:这也可以...
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.)
从.NET 4.5开始,您可以使用async事件处理程序和Task.Delay来获得相同的行为。简单地让UI在这样的处理程序期间更新,返回Dispatcher.Yield。
发布于 2018-07-14 01:56:29
这是一个使用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();https://stackoverflow.com/questions/6117293
复制相似问题