Rez*_*eza 4 c# wpf multithreading invoke invokerequired
那里.我正在使用C#.wpf,我从C#source获得了一些代码,但我无法使用它.有什么我必须改变的吗?或者呢?
// 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;
}
}
Run Code Online (Sandbox Code Playgroud)
如上面的代码,错误在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 });
}
}
Run Code Online (Sandbox Code Playgroud)
您可能从Windows窗体中获取了该代码,其中每个Control都有一个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 });
}
Run Code Online (Sandbox Code Playgroud)
此外,你没有SetText
正确打电话.它需要两个参数,在C#中用逗号分隔,而不是等号:
SetText(currentIterationBox.Text, iteration.ToString());
Run Code Online (Sandbox Code Playgroud)
在WPF中,你不使用Control.Invoke但Dispatcher.Invoke像这样:
Dispatcher.Invoke((Action)delegate(){
// your code
});
Run Code Online (Sandbox Code Playgroud)
使用
Dispatcher.CheckAccess()
Run Code Online (Sandbox Code Playgroud)
先检查一下.
归档时间: |
|
查看次数: |
9090 次 |
最近记录: |