Accessing form control in separate thread.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a Windows Forms application with a ProgressBar control on a form.

In that form, I create a new process to run another program. I register an
event handler for the Exited() event.

I start the progressbar scrolling (Marquee) and start the process.

When the process exits, I want to stop the progress bar. However, when I try
to access the ProgressBar control, I get a System.InvalidOperationException.
"Cross-thread operation not valid: Control 'progressBar1' accessed from a
thread other than the thread it was created on."

What can I do in this case to access the progressBar?

Thanks,
Jeff
 
Check InvokeRequired property for control and related Multithreaded Control
Sample in MSDN

HTH
Alex
 
Hi Alex.

Thanks for the info. How do I go about finding this "Multithreaded Control
Sample" in MSDN. I have read up on the Invoke, BeginInvoke etc methods but
really need to see a C# example to figure this out.

Thanks,
Jeff
 
That example was long and involved. So thought I would post a simpler
delegate example for C#.

public class form1 : form
{
private delegate void myDelegate();
private myDelegate theDelegate;

public form1()
{
theDelegate = new myDelegate(delegateMethod);
}

private void delegateMethod()
{
// modify form controls
}

void process_Exited(Object sender, EventArgs e)
{
// this event occurs in a different thread from the form1 class
constructor
myFormControl.Invoke(theDelegate);
}
}
 
One last point to consider is BeginInvoke against Invoke. Look up
differences between synchronous and asynchronous execution. Me personally, I
prefer BeginInvoke

Glad you were able to sort this out

Alex
 
Thanks again Alex. I chose synchronous as the form update needs to occur only
after the asynchronous process exits. So there isn't any more work being done
in the background and synchronous works just as well as async. As I
understand it, that is the only difference. But correct me if I am missing
something please.

Jeff
 
Back
Top