views:

65

answers:

3

I'm not (intentionally) using threads in my C# app. In fact my main method has a [STAThread], which I thought meant I'd only be using one thread.

Why then, would I be getting this error message?

Cross-thread operation not valid: Control 'messageLog' accessed from a thread other than the thread it was created on.

+2  A: 

Marking your main method with [STAThread] does not mean that you cannot spawn additional threads.

You don't really provide any information about what is triggering your code, so I can't be more specific, but any time you execute asynchronous code it will take place on another thread. Doing things like BeginInvoke on a delegate (or, for that matter, most methods that start with Begin--and definitely if they return an IAsyncResult--are async methods) will execute the code (and the callback) on another thread.

If you can provide some more detail about your situation, I can try to give more specific advice.

Adam Robinson
+6  A: 

There are a couple of types which can cause your code to run on different threads without any explicit call to System.Threading. In particular FileSystemWatcher and BackgroundWorker come to mind. Are you using any of these types?

Also STAThread in no way limits the ability of your process to spawn threads. It instead sets the COM apartment type of the initial application thread.

JaredPar
System.Timers.Timer being another
nos
@Nos I am using timers - I guess that's what's caused it.
Tom Wright
Use System.Windows.Forms.Timer if this is a winfoms application, it'll dispatch timer events to the GUI thread.
nos
That fixed it! Thanks @Nos!
Tom Wright
A: 

[STAThread] does not indicate that your application will be single threaded. It only indicates that the application will use threading a manner that allows other threads to execute while a particular thread is waiting for a time-consuming operation to complete.

As to why the cross threading exception is being thrown, a little more context is needed. What type of control is messageLog? What code accesses this control? Are you using any other controls that implicitly use threads (such as a BackgroundWorker)?

Harry Steinhilber