c# - 跨线程操作

标签 c# multithreading

谁能告诉我 if 和 else 语句在这个函数中是如何相关的。我正在显示从另一个线程到 GUI 线程的文本。执行的顺序或方式是什么。 else语句有必要吗?

delegate void SetTextCallback(string text);

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox7.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox7.Text = text;
        }
    }

最佳答案

  1. 另一个线程调用SetText
  2. 因为它不是创建表单的线程,所以它需要 Invoke
  3. this.Invoke 使用给定参数再次调用 SetText。还要检查 this
  4. 现在 SetText 是从 UI 线程调用的,不需要 Invoke
  5. else block 中,我们确定文本已安全设置为线程

关于c# - 跨线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14704483/

相关文章:

c++ - 使用尽可能多的CPU核心编写 super UDP服务器

c# - 为什么在使用结构作为通用字典键时 C# 会产生垃圾?

c# - 当我在服务器端使用 RadGrid telerik 控件运行 asp.net 网页时,它会生成错误吗?

java - 如何通过共享对象正确使用信号?

c++ - 是否可以获取 atomic_int 的底层存储地址?

C HTTP 服务器 - 多线程模型?

c# - 两个 .Net 应用程序之间的高效通信

c# - 用于验证多个值范围的正则表达式 (.NET)

c# - 如何在 .NET C# 中为 HTTP/2 服务器实现 TLS-ALPN

c# - 我如何确定我的所有线程何时完成执行?