简体   繁体   中英

thread Invocation in C# .WPF

there. I'm using C#.wpf, and I get this some code from C# source, but I can't use it. is there anything that I must change? or do?

 // 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;
        }
    }

As above code, the error is in InvokeRequired and Invoke

the purpose is, I have a textbox which is content, will increment for each process.

here's the code for the textbox. SetText(currentIterationBox.Text = iteration.ToString());

is there anything wrong with the code?

thank you for any help

EDIT

// 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 });
        }
    }

You probably took that code from Windows Forms, where every Control has a Invoke method. In WPF you need to use the Dispatcher object, accessible through a Dispatcher property:

 if (control.Dispatcher.CheckAccess())
 {
     control.Text = text;
 }
 else
 {
     SetTextCallback d = new SetTextCallback(SetText);
     control.Dispatcher.Invoke(d, new object[] { control, text });
 }

Additionally, you're not calling SetText correctly. It takes two arguments, which in C# are separated with commas, not with equal signs:

SetText(currentIterationBox.Text, iteration.ToString());

In WPF you dont use Control.Invoke but Dispatcher.Invoke like this:

Dispatcher.Invoke((Action)delegate(){
  // your code
});

Use

Dispatcher.CheckAccess()

to check first.

In WPF using next construction:

if (control.Dispatcher.CheckAccess())
{
   ...
}
else
{
   control.Dispatcher.Invoke(...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM