and has 1 comment
Trying to build a reusable object that is independent of the Windows or Web interface I've stumbled upon the issue of multiple threads trying to access and modify the same form. The ugly "Controls created on one thread cannot be parented to a control on a different thread." error occured and, no matter what I tried, it seemed it will never work. But finally I found out the solution.

First the issue:
doing something on the interface was starting a separate process that ran an external program. The interface has a progress bar that was updated during this. At the end of the process, an event was fired, and to that event I added a method that was supposed to clear the progress bar and put another UserControl on the form. The the error occured.

The problem was that the event was fired by the separate process that ran the external program. Trying to change something in the form that was created on another thread resulted in error.
The solution is that inside the method called by the event any references to methods that change the interface must be done through BeginInvoke:

private delegate void MethodDelegate(int i)

private void TestMethod(int i) {
// change interface here
}

private void OnEvent(object sender, EventArgs e) {
<interface_form_object>.BeginInvoke(new MethodDelegate(TestMethod),new
object[] {i});
// this replaces using TestMethod(i) which generates an error
}

Update on this:
Use the BackgroundWorker class in NET 2.0.

Comments

Post a comment