C# 访问UI组件并由Xamarin中的另一个线程覆盖它

C# 访问UI组件并由Xamarin中的另一个线程覆盖它,c#,android,multithreading,xamarin,invoke,C#,Android,Multithreading,Xamarin,Invoke,所以我已经试着解决这个问题好几个小时了,我几乎放弃了。 必须有一种方法可以通过另一个线程访问Xamarin C#代码上的正常标签 我基本上就是这么做的: namespace Traktor { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TrackerPage : ContentPage { public delegate void TrackedTimeUp

所以我已经试着解决这个问题好几个小时了,我几乎放弃了。 必须有一种方法可以通过另一个线程访问Xamarin C#代码上的正常标签

我基本上就是这么做的:

namespace Traktor
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TrackerPage : ContentPage
    {
        public delegate void TrackedTimeUpdateHandler(double elapsedTime);    // Delegate to notify the TrackingPage of how much time elapsed
        private TimeTracker tracker;

        // Ctor, and other methods etc. are here
        // ...

        // Initialize the tracker and add handler to it (called in Ctor)
        void Initialize()
        {
            tracker = new TimeTracker();
            tracker.TrackedTimeUpdate += new TrackedTimeUpdateHandler(UpdateGUI);
        }

        // This method is called periodically by the inner thread of 'tracker'
        void UpdateGUI(double elapsedTime)
        {
            // Status label is a label on the page this refers to
            statusLabel.Text = String.Format("{0:F2}", elapsedTime); 
            // Throws exception: "Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.'"
        }
    }
}
TimeTracker
中运行一个单独的线程,它不断引发一个事件来通知此tracker页面经过了多少时间。然后调用
UpdateGUI(…)
-方法。这只是将statusLabel的文本设置为经过的时间。每件事都很有魅力。但是我不能通过UI线程本身以外的其他线程访问
statusLabel.Text

我已经试了很多次了,但令人恼火的是什么都不起作用,因为大多数情况下,有些东西不见了,或者其他东西不起作用。例如,statusLabel不是实现
ISynchronizeInvoke
的类,或者我不能使用
System.Windows.Forms.Control
-命名空间。我不知道为什么

所以我的问题是: 是否有方法访问标签(my
ContentPage
上UI的一部分)并从另一个线程对其进行修改(或以任何方式使
elapsedTime
可以定期显示)?我不能调用和异步似乎不适合这里。我真的不知道如何避开这个问题。或者在UI线程上是否有一种Xamarin本地调用方式


到目前为止我所尝试的:

  • 一,

  • 二,

  • 三,

  • 四,

->我无法使用
System.Windows.Forms.Control
-命名空间。我不知道为什么。也许是因为Xamarin不想让我这么做。因此,
System.Windows.Forms.Control.Invoke等我无法访问。

包含一个帮助程序类,用于强制代码在主UI线程上执行

MainThread.BeginInvokeOnMainThread(() =>
{
    // Code to run on the main thread
});

非常感谢你!我真的不知道为什么我没有偶然发现。你能回答吗?或者我应该回答这个问题,这样我就可以宣布这个问题已经结束了吗?有趣的是,我试过了,但没有成功。我试的那几秒钟,这确实奏效了。我不知道,但很奇怪。无论如何,非常感谢你!这真的帮助了我!