-1

I know Winforms has only one UI thread, and if you need to update it while you are on another thread, you should use invoke method.

My questions is if what you are doing does not change the look of any control, would that still be accessing the UI thread?

For example, my form1 has a logger which write messages to a local file which users don't see at all. If I use the logger in another thread, say write a new message, would this be considered accessing the UI thread? Yes, logger is initialized in form1.cs, but it has no visual representation on the form at all. Do I still need to use invoke?

Also, if I have a custom control which extends a textbox. The custom control has a property called initialized. Changing this property has no effect on the look of the control whatsoever. Then, if I update this property from another thread, do I need to use the invoke method?

Girl Spider
  • 330
  • 2
  • 6
  • The lack of the cross-thread exception doesn't prove that the code is thread-safe. There are lots of other ways to break thread-safety. Your question is too broad, lacking sufficient detail to know how the "logger" you describe is used. It's likely that from the **GUI** point of view it's fine; the cross-thread exception involves _only_ Winforms objects which have thread-affinity. But if the logger can be accessed from other threads (and if not, why is it not being allocated in the single thread that will use it?), then you have other thread-safety issues. – Peter Duniho Aug 16 '20 at 18:48

2 Answers2

0

If only one thread uses the logger instance, no need to synchronize, else if several threads can write to it, you need to synchronize, not with the UI thread but between threads, using lock or monitor for example.

It is the same thing for the last question.

  • Here source code for the "last question" - https://github.com/dotnet/winforms/blob/master/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs#L2636 - if the property won't check InvokeRequired than every thing is fine – Rand Random Jun 17 '20 at 17:06
-2

Simple experiment seems to say if you are not changing the looks of a control, then you are thread safe.

enter image description here

You can see in the screenshot, when I set a member of my form call blnButtonDown(a bool), it was OK. When I changed the name of a textbox of my form, it was still OK. It was only when I changed the textbox's text, which changes the look of the form, that I got an exception thrown.

So my tentative conclusion is that if you are changing a form/control from another thread, you don't have to use invoke if your changes do not change the look of the form/control.

Girl Spider
  • 330
  • 2
  • 6