Thanks Michael. Using BeginInvoke as I showed in the blog could have some slight side effects depending on what you expect. I might update that sample like so using blocking Invoke instead:
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();
}
--
William Stacey [MVP]
"Michael Nemtsev" <ne*****@msn.com> wrote in message news:9c**************************@msnews.microsoft .com...
| Hello Arv,
|
| That's why we are here.
|
| If you use .NET 2.0 there is more elegant way for doing this
| read there http://spaces.msn.com/staceyw/blog/cns!F4A38E96E598161E!652.entry
|
|
| AC> Hi Vadym.
| AC> I always get amazed about how fast I do get replys from you guys.
| AC> Thanx a lot, I now got it to work... =)
| AC> /Arv
| AC>
| AC> "Vadym Stetsyak" wrote:
| AC>
| >> Hello, Arv!
| >>
| >> AC> "An unhandled exception of type
| >> 'System.InvalidOperationException' AC> occurred in
| >> System.Windows.Forms.dll
| >>
| >> AC> Additional information: Cross-thread operation not valid: Control
| >> AC> 'textBoxStatus' accessed from a thread other than the thread it
| >> was AC> created on."
| >>
| >> To use winforms control from separate thread you should call
| >> Control.Invoke method. In your case this will be TextBox.Invoke
| >>
| >> The code may look like this:
| >>
| >> delegate void OutputUpdateDelegate(string data);
| >>
| >> public void UpdateTextBox(string data)
| >> {
| >> if ( txtOutput.InvokeRequired )
| >> txtOutput.Invoke(new OutputUpdateDelegate(OutputUpdateCallback),
| >> new object[] { data });
| >> else
| >> OutputUpdateCallback(data); //call directly
| >> }
| >> private void OutputUpdateCallback(string data)
| >> {
| >> txtOutput.Text += data;
| >> }
| >> UpdateTextBox method can be called from other threads
| >> --
| >> Regards, Vadym Stetsyak
| >> www:
http://vadmyst.blogspot
| ---
| WBR,
| Michael Nemtsev :: blog:
http://spaces.msn.com/laflour
|
| "At times one remains faithful to a cause only because its opponents do not
| cease to be insipid." (c) Friedrich Nietzsche
|
|