【发布时间】:2017-01-03 12:01:48
【问题描述】:
我有一个这样定义的单例:
public partial class MoonDataManager
{
static MoonDataManager _singletonInstance;
public static MoonDataManager SingletonInstance
{
get
{
return _singletonInstance;
}
private set
{
_singletonInstance = value;
}
}
我有一个安全地创建实例的函数:
public static async Task<MoonDataManager> CreateSingletonAsync()
{
_singletonInstance = new MoonDataManager();
我应该:
return _singletonInstance; (field)
或
return SingletonInstance; (property)
我关心垃圾收集,尤其是在 Xamarin 中的 iOS 或 Android 中。
此外,如果 C# 中有此命名模式,请告诉我是否偏离标准。
更新:
现在我想我真的被线程和异步方法困住了。以下是对象及其目标:
MoonDataManager:每个表运行一次RegisterTable<Models.IssuerKey>。这是一个基本运行(new MobileServiceSQLiteStore).DefineTable<T>() 的通用方法
OfflineStore:这是一个MobileServiceSQLiteStore。MobileClient:这是一个MobileServiceClient。MoonDataManager依赖关系:MoonDataManager 需要 OfflineStore 和 MobileClient 才能完成初始化。具体来说,它执行MobileServiceClient.SyncContext.InitializeAsync(OfflineStore)
我不确定如何理解这种意大利面条式的依赖关系......或者如何使代码看起来不错,并且是线程安全的。
这是代码的新迭代:
private readonly Lazy<MobileServiceClient> lazyMobileClient =
new Lazy<MobileServiceClient>(() => new MobileServiceClient(Constants.ApplicationURL), true); // true for thread safety
public MobileServiceClient MobileClient { get { return lazyMobileClient.Value; } }
private readonly Lazy< MobileServiceSQLiteStore> offlineDB =
new Lazy<MobileServiceSQLiteStore>(() => new MobileServiceSQLiteStore(Constants.OfflineDBName), true ); // true for thread safety
private MobileServiceSQLiteStore OfflineStore { get { return offlineDB.Value; } }
private static readonly Lazy<MoonDataManager> lazy = new Lazy<MoonDataManager>(() => new MoonDataManager(), true); // true for thread safety
public static MoonDataManager Instance { get { return lazy.Value; } }
private MoonDataManager()
{
MoonDataManager.Instance.RegisterTable<Models.IssuerKey>();
// Initialize file sync
// todo: investigate FileSyncTriggerFactory overload.
//Was present on Mar 30, 2016 Channel9 https://channel9.msdn.com/events/Build/2016/P408
MoonDataManager.Instance.MobileClient.InitializeFileSyncContext
(new IssuerKeyFileSyncHandler(Instance), Instance.OfflineStore);
// NOTE THE ASYNC METHOD HERE (won't compile)
await MoonDataManager.Instance.MobileClient
.SyncContext.InitializeAsync(MoonDataManager.Instance.OfflineStore,
StoreTrackingOptions.NotifyLocalAndServerOperations);
}
【问题讨论】:
-
仅供参考它不是线程安全的方式。阅读this
-
仅供参考 - 我也在尝试这种方法:forums.xamarin.com/discussion/25881/…(由 rene_ruppert 评论)
标签: c# xamarin.ios garbage-collection xamarin.android automatic-ref-counting