5

为了尝试在精神上掌握线程,我尝试了 monkey-see-monkey-do,并从MSDN 上的THIS_PAGE复制(如读取和键入,而不是剪切和粘贴) 。

当我这样做时,我收到以下错误

错误 2 找不到类型或命名空间名称“SetTextCallback”(是否缺少 using 指令或程序集引用?) Form1.cs 385 17 ZYX987

错误 3 找不到类型或命名空间名称“SetTextCallback”(是否缺少 using 指令或程序集引用?) Form1.cs 385 41 ZYX987

我在网页上向下滚动,发现很多社区评论表明每个人都有完全相同的问题,因为该示例具有误导性。即,SetTextCallback从未声明过。

这是我在盯着 MSDN 页面时输入的山寨版...

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.label1.InvokeRequired)                    
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.label1.Text = text;
    }
}

请有人在这里建议我应该SetTextCallback在我的 CopyCatCode 中放置的位置吗?

第二个问题:声明它的语法是什么样的?

第三个问题:如果SetTextCallback是一种方法,那么它应该是什么?

我在 Stack Overflow 上搜索了“...SetTextCallback ...”(无引号)并找到了一些参考资料,但不是这个确切的问题。希望这是属于这里的问题。谢谢阅读。

4

4 回答 4

10

在链接到的 msdn 页面中向下滚动(“如何:对 Windows 窗体控件进行线程安全调用”),完整的源代码列在底部。你会在那里找到定义:

    // This delegate enables asynchronous calls for setting
    // the text property on a TextBox control.
    delegate void SetTextCallback(string text);
于 2013-01-09T01:30:14.430 回答
3

SetTextCallback 将只是一个与它委托的方法具有相同签名的委托。

喜欢:

public delegate void SetTextCallback(string message);

您也可以从本教程中受益

于 2013-01-09T01:30:05.927 回答
3

查看完整示例:

// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.
delegate void SetTextCallback(string text);
于 2013-01-09T01:31:55.173 回答
2

我有同样的问题,这是我的解决方案

我正在读取带有 datareceived 的串行端口,只需将收到的文本放入文本框中,我就这样做了:

public void puerto_serie_DataReceived(object sender,
                                   System.IO.Ports.SerialDataReceivedEventArgs e)
{
  string a = this.puerto_serie.ReadLine().Trim();
  leer(a);
}
delegate void SetTextCallback(string text);
void leer(String b)
{
  if (valores.InvokeRequired)
  {
    SetTextCallback d = new SetTextCallback(leer);
    this.Invoke(d, new object[] { b });
  }
  else
  {
    valores.Text += this.puerto_serie.ReadLine().Trim()+"\n";
  }
}
于 2013-04-26T05:47:00.413 回答