Home c# Why doesn't "System.InvalidOperationException" appear?

Why doesn’t “System.InvalidOperationException” appear?




Recently started looking into Thread and Invoke and ran into a problem.
Why is the following code executed without Exception :

private void button1_Click (object sender, EventArgs e)
  Thread thread = new Thread (DoStuff1);
  thread.Name = "new thread";
  thread.Start ();
private void DoStuff1 ()
  this.label1.Invoke ((MethodInvoker) (() = & gt; label1.Text = "info from new thread"));
  button1.BackColor = Color.Red;
  DoStuff2 ();
private void DoStuff2 ()
  label1.Text = "info from new thread";

I wonder why the body of the DoStuff2 method is executed, because we are still accessing a control that was created in another thread.
And by the way, if the text itself is slightly changed in DoStuff2 , for example, to info from new thread2 , then there will already be Exception . Is this some feature of the language, it checks that the text itself does not change and does not cause the assignment of the text? And why is it also executed without Exception button1.BackColor = Color.Red , here we are also referring to the control?

Answer 1, authority 100%

Properties of some controls are not protected from changes from streams, that’s all. Perhaps this was done for optimization purposes, because it would still take some time to check the synchronization context, perhaps for some other reason.

That is, referring to Label in this way is permissible, but the integrity of the data in the Text property is your responsibility, since the probable problems during concurrent editing of the property of this control have not gone away. .NET just lets you do it.

In fact, exceptions when accessing controls from a third-party thread are not taken from nowhere, but only where .NET developers have built this check in order to protect us from the most popular errors when working in multithreading conditions.

WPF has an example where a similar exception is thrown when using a regular collection – ObservableCollection , when used in a UI sync context. When trying to modify a collection from a third-party thread, a NotSupportedException will pop up, the reason is exactly the same as in your question. And this is not a control at all.

So get rid of the template, that this is a certain feature of controls – not to allow themselves to be changed from threads, this is just a decision of the .NET developers where to add a check and where not.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions