Hi Kosmas,
Kosmas Nikolaidis said:
Hi,
I want to fill a datagrid from a separate thread.
How i use the invoke method?
thanks
It seems you know that you cannot touch UI controls or any objects linked to
them, like a data source, from a thread that is not the UI thread that hosts
the UI control. Invoke allows you to synchronize access to the UI controls
or objects linked to them. An excerpt from the documentation on Invoke:
[Invoke] Executes the specified delegate on the thread that owns the
control's underlying window handle.
What Invoke does is post a delegate to the "event queue" of the UI thread
hosting the control. Invoke then blocks until the UI thread has executed the
delegate.
Back to your question. There are two strategies to filling the grid. (1)
Fill the grid in one shot, or (2) Fill the grid in chunks. The first is the
easiest way. I'll illustrate with two examples.
(1) The producer thread produces a DataTable, then Invoke's a method on the
DataGrid that replaces the grid's data source with the produced DataTable.
(2) The producer thread produces rows. When it has produced more than a
certain number of rows (for instance every 100 rows), it Invoke's a method
on the DataGrid that appends the produced rows to the data source of the
grid.
A good article on threading in .NET that might help you further is
http://www.yoda.arachsys.com/csharp/threads/
Hope this helps,
Tom T.