RunOnUiThread 方法的问题 [英] Issues with RunOnUiThread Method

查看:39
本文介绍了RunOnUiThread 方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是我的 Xamarin 应用程序可能在其主线程上做了太多工作".为了规避这个问题,我试图使用 RunOnUiThread 方法.但是,我目前陷入困境,因为我真的不知道如何正确使用它.到目前为止我认为我必须从我当前的活动中运行这个方法.我尝试通过以下方式获得此活动:

I'm facing the issue that my Xamarin application "may be doing too much work on its main thread". To circumvent this issue, I'm trying to move some heavy computations to their own separate threads using the RunOnUiThread method. However, I'm currently stuck as I don't really get how to use it properly. What I figured so far is that I have to run this method from my current activity. I try to obtain this activity via:

var activity = (Activity)Android.App.Application.Context;

作为Xamarin.Forms.Forms.Context;"已过时.不幸的是,我的代码只会导致以下异常:

as "Xamarin.Forms.Forms.Context;" is obsolete. Unfortunately, my code only results in the following exception:

System.InvalidCastException:指定的转换无效.

System.InvalidCastException: Specified cast is not valid.

因此,我有两个问题:

  1. 如何获取当前活动?
  2. 获得活动后调用 RunOnUiThread 方法的最佳方法是什么?

非常感谢您的帮助.

推荐答案

我终于能够用下面的代码解决这个问题:

I was finally able to solve this issue with the following code:

        Context Context = DependencyService.Get<AndroidPropertyHandler>().GetMainActivityContext();
        var Activity = (Activity) Context;
        Runnable MyRunnable = new Runnable(() => {
            Debug.WriteLine("My work goes here...");
        });
        Activity.RunOnUiThread(MyRunnable);

,其中AndroidPropertyHandler"是一个接口,提供对静态上下文的访问.

, where "AndroidPropertyHandler" is an interface providing access to the static context.

这篇关于RunOnUiThread 方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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