DataGridView 在多线程中使用可能出现大红叉

今天做了一个多线程实现 DataGridView 动态更新数据,但是在动态实现更新数据达到20次左右时,DataGridView 突然变成一个大红叉。

如下图所示:

image.png

这种问题的出现属于非常罕见的情况,绝大部分时间是正常的。

通过查询,解决如下:



老外的解释:

The DataGridView is a common .Net control used to display and permit editing of tabular data. It can be filled in via code or by attaching a data source to it. 

DataGridViews, like most controls, are not thread-safe. That is, you need to perform operations on them using the same thread as they were created on. However, sometimes OpenSpan developers will accidently modify the DataGridView from another thread because the operation is coming from an event in another application. 

A safe way to correct this problem and to ensure it doesn't accidently happen is to postpone updating the control during a OnPaint() event if it happens from another thread. This is done by handling an exception and then flagging the control to be redrawn when the MessagePump is run. You can do this by creating a .Net class that inherits from DataGridView and overrides the OnPaint() event. You will need access to a C# compiler to build this. Once built, you add it to the OpenSpan Studio Toolbox and replace your DataGridView controls with it.

(引用地址: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 wstest

{

    class DataGridViewForWs : DataGridView

    {

        protected override void OnPaint(PaintEventArgs e)

        {

            try

            {

                base.OnPaint(e);

            }

            catch

            {


                Invalidate();

            }

        }


    }

}


使用封装的控件以后,经过多次测试,没有再出现大红叉!



--------------------- 

作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864