如何从datagridview跨线程C#中读取 [英] How to read from a datagridview cross-thread C#

查看:539
本文介绍了如何从datagridview跨线程C#中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Form1中有一个DataGridView控件,我试图从运行在单独线程中的类中强制使用.Refresh()和.DataSource.

I have a DataGridView control in Form1 that I am trying to force a .Refresh() and .DataSource from a class which is running in a seperate thread.

在搜索google之后,由于一般的不允许跨线程..."错误持续存在,因此我一无所知.

After searching google I've came up clueless since the general "cross-threading is not allowed..." error keeps persisting.

预先感谢...

推荐答案

SynchronizationContext是现在更好的方法,用于从跨线程更新Form的控件:

SynchronizationContext is the better way now, to update Form's control from cross-threads:

CS:

public partial class MainForm : Form
{
    private readonly SynchronizationContext _context;

    public MainForm()
    {
        InitializeComponent();
        // the context of MainForm, main UI thread
        // 1 Application has 1 main UI thread
        _context = SynchronizationContext.Current;
    }

    private void BtnRunAnotherThreadClick(object sender, EventArgs e)
    {
        Task.Run(() =>
                 {
                     while (true)
                     {
                         Thread.Sleep(1000);
                         //lblTimer.Text = DateTime.Now.ToLongTimeString(); // no work
                         UpdateTimerInMainThread(); // work
                     }
                 });
    }

    private void UpdateTimerInMainThread()
    {
        //SynchronizationContext.Current, here, is context of running thread (Task)
        _context.Post(SetTimer, DateTime.Now.ToLongTimeString());
    }

    public void SetTimer(object content)
    {
        lblTimer.Text = (string)content;
    }
}

希望获得帮助.

这篇关于如何从datagridview跨线程C#中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆