Question

I searched and got that Dispatcher CheckAccess can be used in place of InvokeRequired in wpf.

This is the code want to convert in wpf

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

I tried out this ---->

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

But while running i am getting Error [InvalidOperationException] "The calling thread cannot access this object because a different thread owns it."

What i am doing wrong ? Please Help ?

Was it helpful?

Solution

Your problem is not because of the CheckAccess method... it is fine to use that to check whether the call to Invoke is required or not. When you call the Dispatcher, it is important to ensure that you are calling the correct instance of the Dispatcher class. From the Dispatcher Class page on MSDN:

In WPF, a DispatcherObject can only be accessed by the Dispatcher it is associated with. For example, a background thread cannot update the contents of a Button that is associated with the Dispatcher on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvoke. Invoke is synchronous and BeginInvoke is asynchronous.

So in your case, if you can access the correct Dispatcher instance using the following:

msg_log.Dispatcher.CheckAccess()

Then as @SriramSakthivel mentioned in the comments, you should access the same instance when calling Invoke:

msg_log.Dispatcher.Invoke(new UpdateText(ChangeTextBox), new object[] { txt }); 

OTHER TIPS

OP problem solved but just for record a useful helper for dispatcher check is:

public void DispatchIfNecessary(Action action) {
    if (!Dispatcher.CheckAccess())
        Dispatcher.Invoke(action);
    else
        action.Invoke();
}

which can then be called as:

DispatchIfNecessary(() => { myUIcontrol.Update(...); });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top