Vivek Saurav Vivek Saurav - 1 month ago 12
C# Question

The Calling thread cannot access this object because a different thread owns it,WPF

I have a hardware which is connected through socket,

now i have to check that hardware is connected or not at every 5 seconds which is shown by a checkbox

i have implemented a function :

private static System.Timers.Timer aTimer;
public MainWindow()
{
InitializeComponent();
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
aTimer = new System.Timers.Timer();
aTimer.AutoReset = true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = 2000;
aTimer.Enabled = true;
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (client.Connected == true)
{
Console.WriteLine("Not Connected");
CheckBox.IsChecked = false;
}
else
{
Console.WriteLine("Connected");
CheckBox.IsChecked = false;
}
}


But when i am running the application it is throwing error .

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

I researched and learned about Dispatcher.Invoke but not been able to implement that in my code.

Answer

A ui elememt can only be accessed by one UI Thread. CheckBox Requires UI Thread and your timer runs on different thread. Simple code to use Dispatcher

if (client.Connected == true)
{
    Dispatcher.Invoke(()=>{
        CheckBox.IsChecked =true;
    });
}

OR

if (client.Connected == true)
{
    Dispatcher.Invoke(new Action(()=>{
        CheckBox.IsChecked =true;
    }));
}

if you receive error An object reference is required for the non-static field, method, or property then use this

 Application.Current.Dispatcher.Invoke(() =>
 {
     // Your Code Goes here
 });
Comments