同步等待,而不会阻塞UI线程 [英] Synchronous Wait Without Blocking the UI-Thread
本文介绍了同步等待,而不会阻塞UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个同步的等待功能,不会占用用户界面线程在.NET WPF?是这样的:
子的OnClick(发送者为对象,E作为MouseEventArgs)处理button1.Click
等待(2000年)
UI还在这里处理其他事件
的MessageBox.show(是已经2秒],自你单击该按钮!)
结束小组
解决方案
您可以使用<一个href="http://msdn.microsoft.com/en-gb/library/system.windows.threading.dispatchertimer%28v=vs.90%29.aspx"><$c$c>DispatcherTimer$c$c>对于诸如此类的事情。
编辑:这可能会做的一样好......
私人无效等待(双秒)
{
VAR帧=新DispatcherFrame();
新的Thread((的ThreadStart)(()=&GT;
{
Thread.sleep代码(TimeSpan.FromSeconds(秒));
frame.Continue = FALSE;
}))。开始();
Dispatcher.PushFrame(架);
}
(<一href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx"><$c$c>Dispatcher.PushFrame$c$c>文档。)
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 processes 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.)
这篇关于同步等待,而不会阻塞UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文