【发布时间】:2022-01-04 19:39:30
【问题描述】:
我在 Xamarin.Forms 中对应用单例使用延迟初始化(应用在 iOS 上运行):
public sealed class DataSingleton
{
private static readonly Lazy<DataSingleton> lazy = new Lazy<DataSingleton>(() => new DataSingleton(), LazyThreadSafetyMode.PublicationOnly); // tried withou 2nd parameter as well
public static DataSingleton Instance
{
get { return lazy.Value; }
}
...
}
我在 webserver 中调用它,它运行为 Angular 中的前端提供数据(使用 web 视图显示 Angular 代码)
var server = new WebServer(o => o
.WithUrlPrefix($"http://localhost:{appSettings.ApiPort}")
.WithMode(HttpListenerMode.EmbedIO))
.WithCors()
.WithLocalSessionManager()
.WithWebApi("/api", m => m
.WithController<TestController>()
.WithController<SettingsController>()
.WithController<ReportController>()
.WithController<SystemController>())
.WithModule(new ActionModule("/", HttpVerbs.Any,
ctx => ctx.SendDataAsync(new { Message = "Error" })))
.RunAsync();
在控制器中调用DataSingleton来获取/设置数据,但是app从后台返回后,DataSingleton.Instance为null。
当应用在后台短时间(大约 5 分钟)时,我应该怎么做才能不丢失单例数据
更新 - 我发现这个问题只存在于控制器中,因为当应用程序回到前面时,我可以看到 AppDelegate
WillEnterForeground事件中的所有数据..
【问题讨论】:
-
很好的问题。恕我直言,移动应用程序的底线是您不应该假设 anything 可以在后台运行然后返回应用程序。 (明确编码的后台服务除外。)您当然不应该依赖任何被保留 5 分钟的东西。不幸的是,这意味着依赖
static variables在后台保存的技术并不可靠。一般建议是将所有用户数据和状态保存到持久存储中,释放所有可能的内容,然后在恢复时,从保存的状态重新初始化所有内容... -
... 除非有人有更好的主意,否则您可能必须有初始化代码(每当应用程序从后台返回时),将所有 Lazy 静态变量显式设置为新的 Lazy 实例。或者更好的是,“如果值为空,则创建一个新的懒惰”。我很想知道是否有人对此主题有进一步的见解,以及一般情况下的静态(从背景返回后)!
-
鉴于您的更新,也许您需要在应用程序进入后台时停止该 WebServer,然后在应用程序返回前台时再次运行相同的代码来创建服务器?
-
@ToolmakerSteve 你是对的! WebServer 是一次性的,所以我必须管理它
标签: ios xamarin xamarin.forms xamarin.ios