Reputation:
Basically, what I am trying to do is to create a Singleton instance of Word so my other classes cannot create a duplicate process.
public sealed class WordSingleton
{
private static Word.Application _App = null;
WordSingleton() { }
public static Word.Application App
{
get
{
if (_App == null)
_App = new Word.Application();
return _App;
}
}
// dispose the singleton from a single place
public static void Dispose()
{
if (_App != null)
_App.Quit();
Marshal.ReleaseComObject(_App);
}
}
I have been struggling with this and finally came up with this. I was wondering if the experts can advise me on my usage - if its correct, incorrect, requires improvement? I am coming from a different technology so this is quite new to me.
Upvotes: 2
Views: 442
Reputation: 23123
Here's how I would do this. Use the readonly keyword so that it can't be replaced. This is also threadsafe.
public sealed class WordSingleton
{
public static readonly Word.Application Instance = new Word.Application();
private WordSingleton() { }
}
Upvotes: 3
Reputation: 100328
Why don't initialize in class scope?
private static Word.Application _App = new Word.Application();
Such a singleton will be controlled by CLR. Dispose it as usually.
Upvotes: 1