| InvalidOperationException - But |
| Daniel Schaffer posted at Tuesday, May 02, 2006 4:10 PM |
I don't think I'm cross threading!
I have a Windows form that starts a new thread to do some work with sockets and asynchronous data. I have events in a static class which are used by the second thread to report what happens to the form. These events are handled by the Windows form, and the windows form has methods which are wired to said events which access a status bar that is on the windows form. The problem is, when one of these events from the 2nd thread is handled, I get an InvalidOperationException on a line that only changes text in the form's status bar saying that a thread other than the one that created the status bar is trying to access it.
Before I post a bunch of code for you to wade through, I'll explain in simpler code what I'm doing just to make sure I've got the right idea.
The static class:
public static AsyncObject
{
public delegate void StartedHandler();
public static event StartedHandler Started;
public static void Start()
{
OnStarted();
}
protected void OnStarted()
{ if(Started != null) Started(); }
}
The windows form:
public class UserInterface : System.Windows.Forms.Form
{
Thread workerThread = new Thread(AsyncObject.Start);
StatusBar statusBar = new StatusBar();
public UserInterface()
{
AsyncObject.Started += new StartedHandler(AsyncObject_Started);
workerThread.Start();
}
private void AsyncObject_Started()
{
statusBar.Text = "The worker thread has started!";
}
}
Keep in mind that this is an oversimplification of what I'm doing. I'm sure there are better ways of doing what I did above, but I'm pretty sure that this is what I need to be able to do.
From what I understand of threading, the original thread would be the one calling the "AsyncObject_Started()" method, but that is where I am getting my error. Thanks in advance for any help, and I can post my *actual* code if this looks right. |
 |
|
|
| |
Your code isn't threadsafe |
| Jerry Beckett replied at Thursday, May 04, 2006 6:37 AM |
You will need to use the InvokeRequired method on your statusBar, then set up a delegate and invoke the call on the original thread.
It's all explained here: http://www.codeproject.com/csharp/threadsafeforms.asp
Jerry |
 |
| |
| Odd |
| Daniel Schaffer replied at Thursday, May 04, 2006 11:06 AM |
Thanks, that helped a lot! Is this a new issue in 2.0? Because this same code worked in 1.1. |
 |
| |
| It's more fussy |
| Jerry Beckett replied at Thursday, May 04, 2006 12:48 PM |
.Net 2.0 is a lot more fussy than 1.1, especially in the VS debugger. You might even find that your code works in a runtime environment as it did before.
Jerry |
 |
| |
|
|