首页 > 解决方案 > 如何在 Xamarin 表单的 ContentPage 上使用 RunOnUiThread

问题描述

我想使用 RunOnUiThread 通过 Timer 使用 UI 线程更新 UI(图表和标签)。我正在使用内容页面。如何在 Content Page 上使用为 RunOnUiThread 添加 Activity 类?不支持。

我想做以下事情:

RunOnUiThread(() => { tvTimer.Text = Convert.ToString(CountSeconds );});

目前我正在使用

Device.BeginInvokeOnMainThread(async () => });

用于更新 UI 但 UI 卡住或无法正确更新,例如每秒显示倒数计时器。

请帮帮我

标签: multithreadingxamlxamarin.formsasync-await

解决方案


我认为发生这种情况的原因是因为您可能犯了一些小错误,并且从我看到的代码中我无法做到这一点,所以我将提供一个参考类的东西供您查看:

定义要在主线程上执行的方法:

 private async void MethodOnUIThread()
    {
       await **something**;
       //Probably your timer code 
       //This method does not necessarily have to be async.
    }

在主线程上运行该方法,如下所示:

   Device.BeginInvokeOnMainThread(MethodOnUIThread);

如有查询或您不理解某些内容,请回复


推荐阅读