从 C# 中的子线程更新控件
Updating control from a child thread in c#
我正在尝试从子线程更新按钮控件。
我在将参数传递给新线程时遇到了一些问题。
我收到以下消息:
'UpdateText' 没有重载匹配委托 'System.Threading.ParameterizedThreadStart' (CS0123)
据我所知,ParameterizedThreadStart 接受并输入 "object" 参数。如何在我的 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";
}
}
将 UpdateText 参数更改为对象:
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);
我正在尝试从子线程更新按钮控件。 我在将参数传递给新线程时遇到了一些问题。 我收到以下消息: 'UpdateText' 没有重载匹配委托 'System.Threading.ParameterizedThreadStart' (CS0123)
据我所知,ParameterizedThreadStart 接受并输入 "object" 参数。如何在我的 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";
}
}
将 UpdateText 参数更改为对象:
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);