C#中的线程调用
本文关键字:调用 线程 | 更新日期: 2023-09-27 17:53:28
那里。我正在使用C#.wpf,我从C#源代码中得到了一些代码,但我不能使用它。有什么我必须更改的吗?还是这样?
// Delegates to enable async calls for setting controls properties
private delegate void SetTextCallback(System.Windows.Controls.TextBox control, string text);
// Thread safe updating of control's text property
private void SetText(System.Windows.Controls.TextBox control, string text)
{
if (control.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
Invoke(d, new object[] { control, text });
}
else
{
control.Text = text;
}
}
如上所述,错误在InvokeRequired
和Invoke
中
目的是,我有一个文本框,它是内容,将为每个过程递增。
这是文本框的代码。SetText(currentIterationBox.Text = iteration.ToString());
代码有什么问题吗?
谢谢你的帮助
编辑
// Delegates to enable async calls for setting controls properties
private delegate void SetTextCallback(System.Windows.Controls.TextBox control, string text);
// Thread safe updating of control's text property
private void SetText(System.Windows.Controls.TextBox control, string text)
{
if (Dispatcher.CheckAccess())
{
control.Text = text;
}
else
{
SetTextCallback d = new SetTextCallback(SetText);
Dispatcher.Invoke(d, new object[] { control, text });
}
}
您可能从Windows窗体中获取了该代码,其中每个控件都有一个Invoke
方法。在WPF中,您需要使用Dispatcher
对象,可通过Dispatcher
属性访问:
if (control.Dispatcher.CheckAccess())
{
control.Text = text;
}
else
{
SetTextCallback d = new SetTextCallback(SetText);
control.Dispatcher.Invoke(d, new object[] { control, text });
}
此外,您没有正确调用SetText
。它有两个参数,在C#中用逗号分隔,而不是用等号:
SetText(currentIterationBox.Text, iteration.ToString());
在WPF中,您不使用Control.Invoke,而是使用Dispatcher。像这样调用:
Dispatcher.Invoke((Action)delegate(){
// your code
});
使用
Dispatcher.CheckAccess()
先检查。
在WPF中使用下一个构造:
if (control.Dispatcher.CheckAccess())
{
...
}
else
{
control.Dispatcher.Invoke(...)
}