我有這樣定義的單例:當使用單例模式時,我的公共類是否應返回私有或公共實例?
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](http://csharpindepth.com/Articles/General/Singleton.aspx) – CodingYoshi
僅供參考 - 我也在試驗這種方法:https://forums.xamarin.com/discussion/25881/using-async -in-xamarin-forms(評論由rene_ruppert) – LamonteCristo