我有一个这样定义的单例:
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>
每 table 一次。这是一个本质上运行(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);
}
最佳答案
对于 .NET 4 或更高版本,您可以使用 Lazy<T>
并像这样创建它。
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton(), true); // true for thread safety
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
只有在第一次访问时才会创建它,并且它是线程安全的。
关于c# - 使用单例模式时,我的公共(public)类应该返回私有(private)实例还是公共(public)实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434444/