Sunday, December 19, 2010

.Net Datagridview datasource = datable multi-threading update problem

GUI's Component:
1. datagridview

Controller's Component:
1. Datatable


When GUI's datagridview.datasource = datatable, if you are using another thread to add data into datatable (e.g. dt.rows.Add(datarow), the gui will still try to re-drawn the datagridview even you are not interacting with it.

So, a correct way to insert data into datatable is to make use of delegate and invoke.
 1. Declare a delegate first
Private Delegate Sub DatagridViewNewRowDelegate(ByVal sender As Object, ByVal al As String)

2.  Check if datagridview needs invoke or not.

If datagridview.InvokeRequired then
Dim DeleDatagridRefresh As DatagridViewNewRowDelegate = New DatagridViewNewRowDelegate(AddressOf your function)
            dg.Invoke(DeleDatagridRefresh, sender, "parameter to send")

end if

So, the invoke method will be called in the UI thread that creates the control and the UI won't hang.

This is not the problem of .Net, it is the problem of Win32 API since .Net is just the wrapper of win32 API.

No comments:

Post a Comment