Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Heres an example I put up awhile on my lame blog. Say you wanted to update a label from a worker thread. I've got 4 examples of how to update that label from 1 to 50 using delegates, anon delegates and 2 types of lambdas.</p> <pre><code> private void button2_Click(object sender, EventArgs e) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(); } private delegate void UpdateProgDelegate(int count); private void UpdateText(int count) { if (this.lblTest.InvokeRequired) { UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText); this.Invoke(updateCallBack, new object[] { count }); } else { lblTest.Text = count.ToString(); } } void worker_DoWork(object sender, DoWorkEventArgs e) { /* Old Skool delegate usage. See above for delegate and method definitions */ for (int i = 0; i &lt; 50; i++) { UpdateText(i); Thread.Sleep(50); } // Anonymous Method for (int i = 0; i &lt; 50; i++) { lblTest.Invoke((MethodInvoker)(delegate() { lblTest.Text = i.ToString(); })); Thread.Sleep(50); } /* Lambda using the new Func delegate. This lets us take in an int and * return a string. The last parameter is the return type. so * So Func&lt;int, string, double&gt; would take in an int and a string * and return a double. count is our int parameter.*/ Func&lt;int, string&gt; UpdateProgress = (count) =&gt; lblTest.Text = count.ToString(); for (int i = 0; i &lt; 50; i++) { lblTest.Invoke(UpdateProgress, i); Thread.Sleep(50); } /* Finally we have a totally inline Lambda using the Action delegate * Action is more or less the same as Func but it returns void. We could * use it with parameters if we wanted to like this: * Action&lt;string&gt; UpdateProgress = (count) =&gt; lblT…*/ for (int i = 0; i &lt; 50; i++) { lblTest.Invoke((Action)(() =&gt; lblTest.Text = i.ToString())); Thread.Sleep(50); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload