代码之家  ›  专栏  ›  技术社区  ›  J. Polfer

.NET:Reflector中的Control Invoke()

  •  1
  • J. Polfer  · 技术社区  · 14 年前

    所以,我回到了某个.NET编程中,通过VS.NET 2010中的一个新功能,它检测到一个案例,我试图从一个没有创建控件的线程中修改控件,并向我指出了MSDN上一篇关于如何正确执行此操作的文章。。。

    ' 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
    

    我很兴奋,因为我对如何做到这一点困惑了5年,因为以前版本的vs.net没有标记这一点,因为我是一个项目的本科生,而且。。。

    嗯。。。很抱歉。恢复了镇定。不管怎样,现在我了解了.NET的这一点,我想了解更多关于它的进展和工作原理。

    在哪里可以找到.NET Reflector中Invoke()的代码?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Avram    14 年前

    好吧,让我们在你的例子中说出所有发生的事情。

    1. cross-threading or multi-threading programing (从dotnet的开始就存在)。
    2. 你的 正在使用InvokeRequired的标准功能-这是指, .
      2.a。控件类是Winforms结构的一部分。
    3. Threads .

    article .
    Reflector (我检查了这部分,反射器将向您展示一些与原始代码非常接近的东西。)

        2
  •  1
  •   Sky Sanders    14 年前

    这应该是一个注释,但不能在注释中编码格式,因此。。。。

    如果你用c#这个故事会更简单。。

    private void WriteLog(string text)
    {
      if(InvokeRequired)
      {
        BeginInvoke(new MethodInvoker(()=>{ WriteLog(text); }));
      }
      else
      {
        rtfLog.AppendText(text);
      }
    }
    
        3
  •  0
  •   Andy White    14 年前