因为不同的线程拥有它,WPF调用线程不能访问该对象 [英] The Calling thread cannot access this object because a different thread owns it,WPF

查看:142
本文介绍了因为不同的线程拥有它,WPF调用线程不能访问该对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过socket连接的硬件,

I have a hardware which is connected through socket,

现在我要检查硬件连接,或者没有它是由一个复选框显示每5秒

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

我实现了一个功能:

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 .

,因为不同的线程拥有它调用线程不能访问该对象。

我的研究和了解的 Dispatcher.Invoke ,但仍未能实施,在我的代码。

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

推荐答案

一个UI elememt只能由一个UI线程访问。复选框需要UI线程和你的计时器在不同的线程中运行。简单的代码使用调度

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;
    });
}

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



编辑:How它的工作原理

这篇关于因为不同的线程拥有它,WPF调用线程不能访问该对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆