如何在单独的UI线程中调用基类构造函数

问题描述

我处于需要在单独的线程(即UIThread)中调用我的基类构造函数的情况。我期望的是类似于InvokeOnMainThread(base());的东西。而不是base()

Class BaseClass{
}

Class DerivedClass : BaseClass
{
   public DerivedClass : base()
   {
      ## Constructor
    }
}

请针对这种情况向我提出任何解决方案或解决方法

解决方法

当我们尝试从后台线程实例化UIViewController时

很遗憾,我们无法在非UI线程中实例化UIKit对象,也无法使用UIKit实例。

如果代码在后台线程,任务或回调中执行,则很可能不在主UI线程上执行。

错误消息将显示如下内容:

enter image description here

要解决这些问题,通常我们将使用InvokeOnMainThread方法。

InvokeOnMainThread ( () => {
    // manipulate UI controls
});

否则,您可以向UIThread发送消息以处理您的需求。例如使用 MessagingCenter