简体   繁体   中英

C# wpf dispatcher confusion

how should i go about porting this code to wpf?

public void ChangeTextBox(string txt)
    {
        if (textBox1.InvokeRequired)
        {
            Invoke(new UpdateText(ChangeTextBox), new object[] { txt });
        }
        else
        {
            textBox1.Text += txt + "\r\n";
        }
    }

You can simply use the Dispatcher class of the control or the Application level Dispatcher but in your case you want the control's dispatcher. Also, note that I don't have to recursively call the calling method to invoke it. I can just simply set the textBox.Text to what value you want.

What happens is that it does Context switch behind the scenes and thus allowing your control to be modified because it is being dispatched to its own dispatcher.

if(!textBox1.Dispatcher.CheckAccess())
{
 textbox1.Dispatcher.Invoke(new Action(() => textBox.Text += txt + "\r\n";);
}
else
{
 textBox.Text += txt + "\r\n";
}

You should be able to do something like this:

public void ChangeTextBox(string txt)
    {
        if (!textBox1.Dispatcher.CheckAccess())
        {
            textBox1.Dispatcher.Invoke(new UpdateText(ChangeTextBox), new object[] { txt });
        }
        else
        {
            textBox1.Text += txt + "\r\n";
        }
    }

This answer was based upon a SO question and the MSDN Documentation for Dispatcher .

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