I currently have one single, which can take up to 10 seconds to initialize. However, I do not want my users to punish (expect) this initialization, so I would prefer to load this component into the background thread during application startup. Here is what I have:
Singleton:
public class MySingleton { private static MySingleton _instance; private static readonly object _locker = new object(); private MySingleton() { Init(); } public static MySingleton Instance { if(_instance == null) _instance = new MySingleton(); return _instance; } public void Init() { lock(_locker) { if(_instance != null) return;
Application Launch:
Task.Factory.StartNew(() => MySingleton.Instance.Init());
This code works, protects against double initialization, protects it from the boundary case of the user who needs it, before it is initialized, and also protects it from the fact that someone forgot to call Init ().
However, it feels a bit awkward for two reasons: a) I run the Init method twice at startup. b) I would like to make threads inside a singleton, but something should initiate initialization.
Is there a cleaner / better / better way to handle this?
Thanks in advance for your help.
** EDIT: As stated in the comments, Init was mistakenly restricted to private. It must be publicly available and fixed.
source share