.NET: Control Invoke () in the Reflector

So, I went back to some .NET programming and, using a new feature in VS.NET 2010, I discovered a case where I was trying to change a control from a thread that did not create this control and pointed me to an article on MSDN about how you do it right ...

' HOW TO WRITE TO A FORM CONTROL FROM A THREAD THAT DIDN'T CREATE THE CONTROL ' =========================================================================== ' Say you need to write to a UI text box that logs stuff... Delegate Sub WriteLogDelegate(ByVal [text] As String) Private Sub WriteLog(ByVal [text] As String) If Me.rtfLog.InvokeRequired Then ' We are not in the same thread! ' Create new WriteLogDelegate and invoke it on the same thread Dim d As New WriteLogDelegate(AddressOf WriteLog) Me.rtfLog.Invoke(d, New Object() {[text]}) Else ' We are totally in the same thread... ' Call AppendText like normal! Me.rtfLog.AppendText([text]) End If End Sub 

And I was so excited because I was puzzled by how to do this for 5 years, because previous versions of vs .net did not mark this, since I was a minor in the project and ...

Umm ... I'm sorry that. Compensation restored. Anyway, now that I know this .NET-fu bit, I would like to know more about what is happening and how it works.

Where can I find the code for Invoke () in .NET Reflector?

+1
source share
3 answers

Well, let me name everything that happens in your example.

  • The code you show is cross-threading or multi-threaded programming . (which exist from the beginning of dotnet).
  • Your rtfLog uses the standard features of InvokeRequired - this is the average value that rtfLog inherits from the Control class .
    2.a Management class is part of the Winforms framework.
  • To get a code that "We are not in the same thread!" You need to create two or more Themes .

In general, a reflector can show you an implementation, but an idea that you can find in the article . <w> If you want you to see the implementation, just compile the short code, as in the answer "code poet", and look at it in Reflector . (I am checking this part, the reflector will show you something that is pretty close to your source code.)

+1
source

It must be a comment, but cannot encode the format in the comments, so ....

If you used C #, this story can be made even simpler.

 private void WriteLog(string text) { if(InvokeRequired) { BeginInvoke(new MethodInvoker(()=>{ WriteLog(text); })); } else { rtfLog.AppendText(text); } } 
+1
source
0
source

Source: https://habr.com/ru/post/1309269/


All Articles