Question Cross-thread operation not valid from a Form running under a separate Thread

DarrelX

New member
Joined
May 15, 2025
Messages
1
Programming Experience
10+
Need help resolving System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'

My C# Windows Forms App on .NET 9 launches a separate Form from the main UI thread and runs it on another thread. Everything works except when I click on the View ToolStripMenuItem I get the InvalidOperationException indicating cross-thread operation is not valid: Control. The click of View does not have any Event handlers that get launched (there are dopdown items under View but II don't get that far). I have another Test ToolStripMenuItem's that I can click just fine and dropdown items under them can be clicked and launch Event handlers fine also.

I have looked over the properties on the menu item and looked over the *.designere.cs code in detail and I don't see anything wrong.

For illustration purposes, the following shows my form and when I click on View I get the cross-thread (InvalidOperationException) but when I click on Test it works and I can click submenu items under Test that actuallly launch Event handers.


Screenshot 2025-05-15 151347.png



Any ideas would be appreciated.
 
Unlike Win32 API Windows programming where you can usually get away with creating windows on different threads (as long as you are carefule with your message pump implementations), WinForms isn't quite as forgiving. Without seeing your code, and just depending on your description, it's very likely that you don't realize that you've accidentally create a control in the wrong thread, or you are trying to invoke a method on a control that was created on another thread.

The best advice I can give is look at the callstack of the exception to figure out which control is throwing the exception. Then very carefully add logging code to record which thread that control was created in, and which thread is trying to use a method on it. It could be something very subtle like a focus change being forced by your one thread which call unfocus on the other window which happens to be in another thread.
 
launches a separate Form from the main UI thread and runs it on another thread

That statement doesn't actually make any sense. There's no such thing as "running a form". Show us the actual code so we can see what you're actually doing. I suspect what you mean is that you're calling a method in that form on a different thread. ALWAYS show us the RELEVANT code.
 
Back
Top Bottom