【问题标题】:Updating control from a child thread in c#从 C# 中的子线程更新控件
【发布时间】:2015-04-07 17:50:31
【问题描述】:

我正在尝试从子线程更新按钮控件。 我在将参数传递给新线程时遇到了一些问题。 我收到以下消息: 'UpdateText' 没有重载匹配委托 'System.Threading.ParameterizedThreadStart' (CS0123)

据我了解 ParameterizedThreadStart 接受并键入“对象”参数。如何在我的 UpdateText 方法中将对象“button1”转换为 Button?

    public delegate void MyDelegate(Control ctrl);
    void Button1Click(object sender, EventArgs e)
    {
        Thread thr =new Thread(new ParameterizedThreadStart(UpdateText));
        thr.Start(button1);
    }

    public static void UpdateText(Control control_button)
    {
        if (control_button.InvokeRequired)
        {
            MyDelegate md = new MyDelegate(UpdateText);
            control_button.Invoke(md, control_button);
        }
        else
        {
                control_button.Text = "Updated";
        }
    }

【问题讨论】:

  • 你可以使用 lamda

标签: c# multithreading invoke


【解决方案1】:

将 UpdateText 参数更改为 Object:

 public static void UpdateText(Object o)
    {
        Control control_button = (Control) o;
        // ... the rest of your code ...

ParametrizedThreadStart 上查看此参考:

同样在这一行,我真的不明白你在尝试什么:

MyDelegate md = new MyDelegate(UpdateText);
control_button.Invoke(md, control_button);

你的意思是:

 control_button.Invoke( () => {
     control_button.Text = "Updated"; 
 });

control_button.Invoke(MyDelegate, control_button);

【讨论】:

  • 谢谢。 "控制 control_button = (控制) o;"解决了这个问题。我创建了一个 MyDelegate 实例并传递给 Invoke。它似乎工作得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多