chore: optimized singleton pattern is lazy and thread-safe

main
DESKTOP-3BO4HSG\ksat 2 years ago
parent 758a21f9ad
commit f265b48e8a

@ -10,7 +10,7 @@ using System.Threading.Tasks;
namespace STranslate.Helper
{
public class ConfigHelper
public class ConfigHelper : Singleton<ConfigHelper>
{
public T ReadConfig<T>()
{
@ -54,7 +54,5 @@ namespace STranslate.Helper
/// </summary>
private static string _ApplicationData => $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\{_AppName}";
private static readonly string _AppName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
private static ConfigHelper _Instance;
public static ConfigHelper Instance { get => _Instance ?? (_Instance = new ConfigHelper()); }
}
}

@ -5,6 +5,18 @@ using System.Runtime.CompilerServices;
namespace STranslate.Helper
{
/// <summary>
/// Generate Singleton
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T : class
{
private static readonly Lazy<T> _instance = new Lazy<T>(()
=> Activator.CreateInstance(typeof(T), true) as T, true);
public static T Instance => _instance.Value;
}
/// <summary>
/// 通知
/// </summary>

@ -9,6 +9,7 @@ using System.Threading.Tasks;
namespace STranslate.Helper
{
//https://github.com/praeclarum/sqlite-net
public class SqliteHelper : IDisposable
{
public SqliteHelper()

@ -474,8 +474,8 @@ namespace STranslate.ViewModel
/// </summary>
public MainWindow Mainwin;
private static MainVM _instance;
public static MainVM Instance => _instance ?? (_instance = new MainVM());
private static Lazy<MainVM> _instance = new Lazy<MainVM>(() => new MainVM());
public static MainVM Instance => _instance.Value;
public Hotkeys NHotkeys;
private bool IsTopmost { get; set; }

@ -110,8 +110,8 @@ namespace STranslate.ViewModel
public ICommand EscCmd { get; private set; }
private static SettingsVM _instance;
public static SettingsVM Instance => _instance ?? (_instance = new SettingsVM());
private static Lazy<SettingsVM> _instance = new Lazy<SettingsVM>(() => new SettingsVM());
public static SettingsVM Instance => _instance.Value;
/// <summary>
/// 是否开机自启

Loading…
Cancel
Save