c# - 为什么我应该使用 methodinvoker 而不是声明一个 void 方法并调用它?

标签 c#

我正在使用异步套接字操作,当客户端收到一条消息时,它使用以下代码调用一个方法并执行 Methodinvoker:

private void AddText(string message)
        {
            MethodInvoker mi = new MethodInvoker(delegate
            {
                textBox1.Text += message;
            });
            this.Invoke(mi);
        }

我不明白为什么要使用 methodinvoker。 最好使用它而不是声明和调用不带参数的 void 方法?一定有充分的理由。

最佳答案

显然你的方法是从另一个线程调用的,然后是你的主线程。

Invoke :

Executes the specified delegate on the thread that owns the control's underlying window handle.

您应该始终在主线程上与您的用户控件进行交互。 Invoke 方法将委托(delegate)发送回应用程序的主线程。

关于c# - 为什么我应该使用 methodinvoker 而不是声明一个 void 方法并调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734950/

相关文章:

c# - 为什么 IsLiteral 对十进制返回 false?

c# - Visual Studio 2010 : How to enforce build order of projects in a solution?

c# - 删除导出到文本文件的列之间的空格

c# - 何时使用闭包的场景

c# 查询内存中的大型只读表

c# - C# PayPal REST API Winforms 应用程序中的授权代码在哪里?

c# - 在 MVVM 中使用 CommandParameter 传递类变量

c# - 删除 GIT 中的一些提交

c# - 为什么我的 WinForms 控件看起来很扁平?

c# - 使用 C# 中的类将数据保存到 SQL DB