Accessing form control in separate thread.

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
 
A

AlexS

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

HTH
Alex
 
G

Guest

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
 
G

Guest

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);
}
}
 
A

AlexS

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top