C#在调用UI刷新时启用了不同的线程,导致数据异常的解决方案
将原先的刷新函数封装如下
原先的调用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public void RefreshGrid() { System.Diagnostics.Debug.WriteLine( "CurrentThreadID:" + System.Threading.Thread.CurrentThread.ManagedThreadId); updateDataBtnOfLock(); mUnReasonableRows?.Clear(); rebarCollectionErrors?.Clear(); this .warningCount.Text = "0" ; Data.Clear(); this .c1FlexGrid1.Cols[9].Visible = TableRebarResultControl.ShouldConsiderBendAdjsutment(); this .c1FlexGrid1.Rows.Count = 1; this .c1FlexGrid1.ClearFilter(); this .totalWeight.Text = "单构件钢筋总重(kg):" ; if (mTargetRebar == null ) return ; mTargetRebar.ValidateCollections( ref rebarCollectionErrors); mTargetRebar.CollectRebars( ref Data); sortBarsByType( ref Data, mTargetRebar); if (Data == null ) return ; List<MRebarCollection> manucol = new List<MRebarCollection>(); foreach ( var rebarCol in Data) { if (rebarCol.HasFlag(MRebarCollection.Flag.ManualAdded)) { manucol.Add(rebarCol); continue ; } AddOneRowData(rebarCol); } foreach ( var col in manucol) { AddOneRowData(col); } } |
修改:1、将原函数的访问权限降低为private,2、更名为_unsafe,3、包装一个新的函数提供外部调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | private void RefreshGrid_unsafe() { System.Diagnostics.Debug.WriteLine( "CurrentThreadID:" + System.Threading.Thread.CurrentThread.ManagedThreadId); updateDataBtnOfLock(); mUnReasonableRows?.Clear(); rebarCollectionErrors?.Clear(); this .warningCount.Text = "0" ; Data.Clear(); this .c1FlexGrid1.Cols[9].Visible = TableRebarResultControl.ShouldConsiderBendAdjsutment(); this .c1FlexGrid1.Rows.Count = 1; this .c1FlexGrid1.ClearFilter(); this .totalWeight.Text = "单构件钢筋总重(kg):" ; if (mTargetRebar == null ) return ; mTargetRebar.ValidateCollections( ref rebarCollectionErrors); mTargetRebar.CollectRebars( ref Data); sortBarsByType( ref Data, mTargetRebar); if (Data == null ) return ; List<MRebarCollection> manucol = new List<MRebarCollection>(); foreach ( var rebarCol in Data) { if (rebarCol.HasFlag(MRebarCollection.Flag.ManualAdded)) { manucol.Add(rebarCol); continue ; } AddOneRowData(rebarCol); } foreach ( var col in manucol) { AddOneRowData(col); } } |
经过包装后,现在对外调用的方式
1 2 3 4 5 6 7 8 9 | public void RefreshGrid() { if ( this .InvokeRequired) this .BeginInvoke( new Action(()=> RefreshGrid_unsafe())); else RefreshGrid_unsafe(); return ; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix