【问题标题】:Xamarin Forms - The application called an interface that was marshalled for a different threadXamarin Forms - 应用程序调用了为不同线程编组的接口
【发布时间】:2018-05-02 13:56:49
【问题描述】:

现在我正在尝试将 Xamarin Forms 与 I2C 设备和 Raspberry Pi 结合使用。我用 C# 编程,Raspberry Pi 与 Windows IoT 一起安装。我遇到了一个关于计时器的问题。

我想做的是创建一个 System.Threading.Timer 并从 I2C 设备读取数据,然后每秒将其显示在标签上,但是当我尝试显示数据时,错误显示“应用程序调用了为不同线程编组的接口。"

以下代码是我尝试做的。

    public void InitSecondTimer(int interval)
    {
        secTimer = new Timer(interval);
        secTimer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        secTimer.Start();
        Debug.WriteLine("Secondtimer inited");
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        double voltage = 0;
        InputI2C(ADC0, ref voltage); //Read data from I2C devices
        ai0.Text = voltage.ToString(); //ai0 is a Label
    }

那么我该如何解决这个问题呢?非常感谢您的帮助!

【问题讨论】:

    标签: c# xamarin timer xamarin.forms


    【解决方案1】:

    System.Threading.Thread.Timer 的 Elapsed 事件在线程池线程上运行,该线程不拥有 ACD0(我假设它是该设备的接口)。相反,您应该使用Xamarin Forms Timer:

    线程

    在计时器中运行的任何代码都将在主 UI 线程上运行。确保您没有阻塞 UI 线程或进行任何密集计算。如果合适,请确保将代码移至后台线程。

    public void InitSecondTimer(int interval)
    {
        Device.StartTimer(TimeSpan.FromMiliseconds(interval), () =>
        {
            double voltage = 0;
            InputI2C(ADC0, ref voltage); //Read data from I2C devices
            ai0.Text = voltage.ToString(); //ai0 is a Label
    
            return true; // True = Repeat again, False = Stop the timer
        });
    
        Debug.WriteLine("Secondtimer inited");
    }
    

    【讨论】:

    • 非常感谢您快速正确的解决方案,效果很好。我非常感谢您立即帮助我并节省了我的时间!太酷了!
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多