0

Say I have a Windows form and then click a button to start a new thread. If in that new thread I change something about the current form, like its background color, Visual Studio will raise an invalid operation exception as I have crossed threads doing UI work.

However, if in that other thread I create a new form and show it, I get no such exception.

Why is that?

Girl Spider
  • 330
  • 2
  • 6
  • 3
    If you created that Form in another Thread and you access it from that Thread, there's no cross-thread access. If you try to access that Form from the default UI Thread (or the other way around)... Is there a specific reason to create a Form in a Thread other than the provided one? Usually there isn't. Maybe you prefer to offload some work to a ThreadPool Thread and resume to the UI Thread to show the results. – Jimi Jan 21 '21 at 18:51
  • Please do not create multiple UI threads, there are very few cases this is a good idea. Keep to one UI thread and use Tasks and async/await to ensure you are doing all the UI updates on the UI thread. – JonasH Jan 21 '21 at 21:48
  • Jimi's answer is quite satisfactory to me. But I don't know how to mark a comment as an accepted answer. I do have a follow up question here: https://stackoverflow.com/questions/65839267/why-cross-thread-exception-only-thrown-when-you-change-visible-properties-of-a-c The reason I need to create multiple UI threads: I have a main form that monitors some machinery and keeps updating the graphics. I have multiple other threads that enable users to simultaneously run different operations on the machine. Some of the operations will have pop up forms to instruct the user or get input from them. – Girl Spider Jan 22 '21 at 04:35

0 Answers0