BeginInvoke复制参数

时间:2013-09-26 18:17:18

标签: c# multithreading winforms begininvoke

尝试学习Invoke / BeginInvoke,我遇到了那个问题。

       // Update UI
       public void UpdateForm(string value) {
        txtLog.AppendText(value + "\r\n");
       }


       // Thread function
       private void readSocket() {
        string row = "";

        while (socket.Connected) {                
            row = socket.readLine();            

            if (IsControlValid(this))
                BeginInvoke((MethodInvoker)delegate { UpdateForm(String.Copy(row)); });                    

        }
    }

使用调用方法,我的UI更新时使用正确的文本,而不是使用 BegineInvoke 我看到错误的文本,即一些文本反复花费很多时间。我知道那个电话

BeginInvoke((MethodInvoker)delegate { UpdateForm(row); });  

也许“行”可以是共享变量而不是

的行为
BeginInvoke((MethodInvoker)delegate { UpdateForm(String.Copy(row)); });                    

我认为每个BeginInvoke调用都会创建一个“新”委托,所以使用String.Copy必须创建另一个字符串实例,但我看到总是错误的值(重复,ecc)。

我哪里错了?

1 个答案:

答案 0 :(得分:5)

  

也许“行”可以是共享变量而不是

的行为

是的,row变量是捕获的 - 所以无论什么时候读取它,都是读取的最新值。您应该将变量声明放在循环中:

while (socket.Connected) {                
    string row = socket.readLine();

    if (IsControlValid(this)) {
        // Removed String.Copy call, as it was pointless
        BeginInvoke((MethodInvoker)delegate { UpdateForm(row); });
    }
}

现在,对于循环的每次迭代,您将拥有一个不同的变量,因此当您在委托中读取它时,不会覆盖一个线程中的先前值。