How do I safely populate with data and Refresh() a DataGridView in a multi-threaded application?

前端 未结 3 597
野的像风
野的像风 2021-02-06 16:42

My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type \"Point\") and a running count of this positio

3条回答
  •  天命终不由人
    2021-02-06 17:08

    Looks like you have your answer right there! Just in cawse you're curious about how to do cross thread calls back to ui: All controls have a Invoke() method (or BEginInvoke()- in case you want to do things asynchronously), this is used to call any method on the control within the context of the main UI thread. So, if you were going to call your datagridview from another thread you would need to do the following:

    public void refreshWindow_Elapsed(object source, EventArgs e)
    {
    
       // we use anonymous delgate here as it saves us declaring a named delegate in our class
       // however, as c# type inference sometimes need  a bit of 'help' we need to cast it 
       // to an instance of MethodInvoker
       dataGridView1.Invoke((MethodInvoker)delegate() { dataGridView1.Invalidate(); });
    }
    

提交回复
热议问题