c# - C# .WPF 中的线程调用

标签 c# wpf multithreading invoke invokerequired

那里。 我正在使用 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;
        }
    }

如上代码,错误在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 });
        }
    }

最佳答案

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

关于c# - C# .WPF 中的线程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5803416/

相关文章:

c# - 有没有办法在xml中使用条件编译符号

WPF 性能加载用户控件

c# - 为什么 ContextMenu Command 和 CommandParameter 在 DataGrid 中不起作用

Java使用另一个线程检查线程的状态

multithreading - FFMpeg 如何使用多线程?

c# - Excel 导入的 SQL 注入(inject)漏洞

c# - 更改评估私有(private)只读属性的顺序

c# - 如何终止线程

C# list of lists - 如何使列表中的列表具有唯一性和抗版本性?

WPF4 Datagrid 不对列标题进行排序