关于C# WPF中的DoEvents,要稳定且快速的,哪位有比较完美的解法?

wShineboy wShineboy 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
RT:使用C#时,相信各位童鞋在WinFrom中没少用Application.DoEvents(如同VB6的DoEvents)。但到了WPF中,这个东西就莫名其妙的被MS忽略了。

在长时间循环处理中,进程阻塞实在难免,网上也有不少DoEvents的解法,效果可以达到,但不是不稳定就是影响速度。下面这一串程序可能比较普及,可惜它不是很稳定,有时会导致窗体停止响应。
        private static DispatcherOperationCallback exitFrameCallback = new DispatcherOperationCallback(ExitFrame);

/// <summary>
/// Processes all UI messages currently in the message queue.
/// </summary>
public static void DoEvents()
{
DispatcherFrame nestedFrame = new DispatcherFrame();
DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, exitFrameCallback, nestedFrame);
Dispatcher.PushFrame(nestedFrame);
if (exitOperation.Status != DispatcherOperationStatus.Completed)
{
exitOperation.Abort();
}
}

private static Object ExitFrame(Object state)
{
DispatcherFrame frame = state as DispatcherFrame;
// Exit the nested message loop.
frame.Continue = false;
return null;
}


后来俺找了个老外写的东西,也能达到类似效果,不过好像有点拖速度——俺的程序需要实时同步单片机的数据,时间很宝贵。
就是这个——
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { }));
...全文
评论 17
收藏 已收藏
分享
返回顶部
wShineboy
C# 111,128 成员 642,537 内容