nanobot
nanobot

Reputation: 15

How to read from a datagridview cross-thread C#

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.

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

Thanks in advance...

Upvotes: 0

Views: 539

Answers (2)

hungndv
hungndv

Reputation: 2141

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;
    }
}

enter image description here

Hope this help.

Upvotes: 0

redmanmale
redmanmale

Reputation: 33

The access to UI elements from another threads is not allowed, so the only way you can do what you want to is using Dispatcher.Invoke() method.

It looks like this:
//Call this code from your another thread (not UI):

Dispatcher.Invoke(()=>
{
    do something in UI-thread
});

Upvotes: 1

Related Questions