C#在调用UI刷新时启用了不同的线程,导致数据异常的解决方案
将原先的刷新函数封装如下
原先的调用方式
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、包装一个新的函数提供外部调用
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); } }
经过包装后,现在对外调用的方式
public void RefreshGrid() { if (this.InvokeRequired) this.BeginInvoke(new Action(()=> RefreshGrid_unsafe())); else RefreshGrid_unsafe(); return; }