multithreading - How to get data from a thread to the UI in C# (How to use backgroundWorker) -
in application, using data grid view. data filled in data grid view in thread.
how can data thread data grid view? how can use background worker this? (please find sample code below)
please help. new c#.
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; namespace ex1 { public partial class form1 : form { public form1() { initializecomponent(); datagridview1.columns.add("1", "sno"); datagridview1.columns.add("2", "time"); datagridview1.columns.add("3", "name"); } public void button2_click(object sender, eventargs e) { // data mythread , add new row datagridview1. //like, datagridview1.rows.add(sno,time,name); // strings mythread } #region event thtead (rx) public void mythread() { // each time button2 press, took data here , add datagridview1 new row. string sno= "some value"; string time="some value"; string name="some value"; } #endregion } }
if want access sno, time , name variables outside mythread() scope, should move declarations outer scope. this:
string sno; string time; string name; public void mythread() { // each time button2 press, took data here , add datagridview1 new row. sno= "some value"; time="some value"; name="some value"; }
to update ui thread, can create class extension method:
public static class extensionmethods { public static void invokeex<t>(this t @this, action<t> action) t : isynchronizeinvoke { if (@this.invokerequired) { @this.invoke(action, new object[] { @this }); } else { action(@this); } } }
and other "data"-thread, can use this:
this.invokeex(f => f.mytextbox.text = "some tekst thread");
but have bring in own action datagrid logic instead of textbox example... this:
this.invokeex(f => f.datagridview1.rows.add(sno,time,name));
in case not familiar this, here's info extention methods:
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
and here's info actions:
Comments
Post a Comment