Posted By: staceyw | Mar 14th, 2006 @ 8:56 AM
page 1 of 1
Comments: 2 | Views: 10391 | Downloads: 92
staceyw
staceyw
Before C# there was darkness...
Here is a simple way to update any UI controls from worker threads using anonymous methods and local variable capture.  Has a more in-line feel.  The single form app is in the zip, but here is the basic logic:







private void button2_Click(object sender, EventArgs e)

{

    this.button2.Enabled = false;

 

    // Worker Thread.

    new Thread(delegate()

    {

        for (int i = 0; i < 100; Interlocked.Increment(ref i))

        {

            // Update UI on UI thread using blocking Invoke.

            this.Invoke((ThreadStart)delegate()

            {

                this.progressBar1.Value = i;

                this.textBox1.Text = "Percent Complete: " + i + "%";

            });

            Thread.Sleep(5);  // Just add a pause to sim work.

        }

 

        // Call any completion code here. All Invokes above must have completed as Invoke is blocking.

        this.Invoke((ThreadStart)delegate()

        {

            this.textBox1.Text = "Percent Complete: 100%";

            this.button2.Enabled = true;

        });

    }).Start();

}


--wjs

Maurits
Maurits
AKA Matthew van Eerde
Very nice.  Reminds me of perl's async BLOCK
Hi wjs,

can you please tell me what will happened anonymous thread which you created?
how do i kill worker thread once work is done?

can you please reply me?

Thanks and Regards
K.Sathishkumar
page 1 of 1
Comments: 2 | Views: 10391 | Downloads: 92