C#.WPF中的线程调用

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)

如上面的代码,错误在InvokeRequiredInvoke

目的是,我有一个内容的文本框,将为每个进程递增.

这是文本框的代码. 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)

R. *_*des 9

您可能从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)

  • @Reza:**什么错误?**为什么你认为他们写错误描述?因为它很有趣?你读过它吗?我打赌它解释了什么是错的. (3认同)

Mar*_*mić 6

在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)

先检查一下.