Hagbard
Hagbard

Reputation: 3700

Issues with RunOnUiThread Method

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;

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

System.InvalidCastException: Specified cast is not valid.

Thus, I have two questions:

  1. How do I obtain the current activity?
  2. What's the best way to call the RunOnUiThread method once I have the activity?

Thank you very much for your help.

Upvotes: 0

Views: 1036

Answers (1)

Hagbard
Hagbard

Reputation: 3700

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

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

Upvotes: 1

Related Questions