1. 程式人生 > 實用技巧 >DataGridView 在多執行緒中使用可能出現大紅叉

DataGridView 在多執行緒中使用可能出現大紅叉

老外的解釋:
TheDataGridViewisacommon.Netcontrolusedtodisplayandpermiteditingoftabulardata.Itcanbefilledinviacodeorbyattachingadatasourcetoit.
DataGridViews,likemostcontrols,arenotthread-safe.Thatis,youneedtoperformoperationsonthemusingthesamethreadastheywerecreatedon.However,sometimesOpenSpandeveloperswillaccidentlymodifytheDataGridViewfromanotherthreadbecausetheoperationiscomingfromaneventinanotherapplication.

Asafewaytocorrectthisproblemandtoensureitdoesn'taccidentlyhappenistopostponeupdatingthecontrolduringaOnPaint()eventifithappensfromanotherthread.ThisisdonebyhandlinganexceptionandthenflaggingthecontroltoberedrawnwhentheMessagePumpisrun.Youcandothisbycreatinga.NetclassthatinheritsfromDataGridViewandoverridestheOnPaint()event.YouwillneedaccesstoaC#compilertobuildthis.Oncebuilt,youaddittotheOpenSpanStudioToolboxandreplaceyourDataGridViewcontrolswithit.
(引用地址:http://wenku.baidu.com/link?url=uLLKAHMKVzub20zu--98KrBOsUnMB5qIa10CXaBjhq-AKHDLifA3V8j5gpM996vglpIq1-4aq26X7-rNJ-t_EbIEqtNtet0TT6rnVRYJh7G

處理的方法,重新封裝DataGridView 控制元件,重新OnPaint 方法,程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;



namespace test { class DataGridViewNew : DataGridView { protected override void OnPaint(PaintEventArgs e) { try { base.OnPaint(e); } catch { Invalidate(); } } } }

使用封裝的控制元件以後,經過多次測試,沒有再出現大紅叉!