WPF不同线程之间的控件是不同访问的,为了能够访问其他线程之间的控件,需要用Dispatcher.Invoke执行一个新的活动即可。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public void SetNotes(string notes) { if (Dispatcher.Thread != Thread.CurrentThread) { this.txtNote.Dispatcher.Invoke(new Action (() => { this.txtNote.Text += notes; this.txtNote.Text += "\r" ; this.txtNote.ScrollToEnd(); })); } else { this.txtNote.Text += notes; this.txtNote.Text += "\r" ; this.txtNote.ScrollToEnd(); } } |
WinForm中:
private delegate void delegateCrossThread(string message); private void SetStatus(string message) { if (this.m_StatusLabel.InvokeRequired == true) { delegateCrossThread ct = new delegateCrossThread(SetStatus); this.Invoke(ct, new object[] { message }); } else { this.m_StatusLabel.Text = message; this.m_StatusLabel.Refresh(); } }
3、异步打开窗口
Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint)); newWindowThread.SetApartmentState(ApartmentState.STA); newWindowThread.Start(); private void ThreadStartingPoint() { SurveyStatWindow surveyStatDialog = new SurveyStatWindow(); if (m_StatDataTable != null) { surveyStatDialog.TimeData = m_StatDataTable; surveyStatDialog.Init(); } surveyStatDialog.ShowDialog(); }
4、全局异步调用
Application.Current.Dispatcher.Invoke( new Action(() => { AddText(); })); this .Dispatcher.Invoke( new Action(() => { AddText(); })); Application.Current.Dispatcher.Invoke( new Action( delegate { AddText();})); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 管理100个小程序-很难吗
· 基于Blazor实现的运输信息管理系统
· 如何统计不同电话号码的个数?—位图法
· 微信支付功能的设计实现与关键实践(UniApp+Java)全代码