The calling thread cannot access this object because a different thread owns it
Try this:
System.Windows.Application.Current.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate
{
// Update UI component here
CheckBox.IsChecked = false;
});
In case you don't want to use Dispatcher for some reason, you could use SynchronizationContext. There is not much difference, but I feel less guilty when using SynchronizationContext as it's not a WPF specific class:
private static System.Timers.Timer aTimer;
private SynchronizationContext _uiContext = SynchronizationContext.Current;
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)
{
_uiContext.Post(new SendOrPostCallback(new Action<object>(o => {
if (client.Connected == true)
{
Console.WriteLine("Not Connected");
CheckBox.IsChecked = false;
}
else
{
Console.WriteLine("Connected");
CheckBox.IsChecked = false;
}
})), null);
}
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(()=> {
// Code causing the exception or requires UI thread access
CheckBox.IsChecked =true;
});
}
OR
if (client.Connected == true)
{
Dispatcher.Invoke(new Action(()=> {
// Code causing the exception or requires UI thread access
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(() =>
{
// Code causing the exception or requires UI thread access
});