Click here to Skip to main content
15,889,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to access the textbox from another class in WPF. The method has been initiated by a thread. And when I am trying to set the textbox value it is getting an error

An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll

Additional information: The calling thread cannot access this object because a different thread owns it.


method called:
C#
Thread tScan = new Thread(MyClass.Start);


method Statusprint called from MyClass.Start() method like,

C#
public static void StatusPrint()
        {
            Instance.txtReport.Text = "value will set here.";
        }


As I am new in WPF so, need your help to get rid of this.

What I have tried:

I tried to do this way.
C#
public static void StatusPrint()
        {
            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new ThreadStart(() => Instance.txtReport.Text = "value will set here."));
        }


here Instance is a static variable declared in MainWindow class initiated to this.
here I am not getting any runtime error but it is just not executing.
Posted
Updated 1-Mar-17 1:31am
v2

Why ThreadStart inside the Dispatcher.CurrentDispatcher? You don't want to start a new thread. Change ThreadStart to Action and it should work.
 
Share this answer
 
Comments
Arkadeep De 1-Mar-17 7:40am    
tried this one with Action. But getting this error..

{System.Windows.Threading.DispatcherOperation}
Dispatcher: {System.Windows.Threading.Dispatcher}
Priority: Normal
Result: null
Status: Pending
Task: Id = 85, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
Pete O'Hanlon 1-Mar-17 7:40am    
My 5.
I have an extension method that I like to use in this case:
C#
public static void BeginInvokeIfRequired(this Dispatcher dispatcher, Action operation)
{
  if (operation== null) return;
  if (dispatcher.CheckAccess())
  {
    action();
  }
  else
  {
    dispatcher.BeginInvoke(action);
  }
}
To call it, all you need to do is this:
C#
Application.Current.Dispatcher.BeginInvokeIfRequired(()=>Instance.txtReport.Text = "value will set here.");
 
Share this answer
 
Comments
Graeme_Grant 1-Mar-17 7:36am    
a neater solution...
Pete O'Hanlon 1-Mar-17 7:40am    
Thanks - I have a similar solution for Dispatcher.Invoke :)
Graeme_Grant 1-Mar-17 7:43am    
I have something similar but did a quick fix to the question asked.
Graeme_Grant 1-Mar-17 8:18am    
my 5 too! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900