I wrote a WCF print MS Word document service. This service is called from multiple PCs. The print method gets as parameter, the MS document path (on the network) and the printer name (printers are on the network).
The problem is when 2 users print on the same time, there could be a chance that the 2 printed documents will be printed on the same printer. The reason is because the way we define where to print the MS document using Word Interop. When printing a word document using interop, we need to set the active printer to the printer name. Therefore, if 2 users print on the same time, the last one that send the print request, will change the active printer and cause the fist document of the first user to be printed on the second printer.
Following the Print method I wrote:
using wd = Microsoft.Office.Interop.Word;
class WordWrapper
{
private readonly wd.Application _wdApp;
public WordWrapper()
{
_wdApp = new wd.Application();
}
internal void Print(string wordPath, string printerName)
{
int referenceCount;
wd.Documents wdDocuments = null;
wd.Document wdDocument = null;
try
{
wdDocuments = _wdApp.Documents;
wdDocument = wdDocuments.Open(wordPath);
try
{
_wdApp.DisplayAlerts = wd.WdAlertLevel.wdAlertsNone;
_wdApp.ActivePrinter = printerName; // THIS LINE CHANGE THE ACTIVE PRINTER
wdDocument.PrintOut();
}
catch (COMException ex)
{
if (ex.ErrorCode == -2146827284)
{
throw new WordFileOpenException();
}
}
finally
{
_wdApp.DisplayAlerts = wd.WdAlertLevel.wdAlertsAll;
wdDocument.Close(true);
wdDocuments.Close();
}
}
finally
{
referenceCount = ReleaseWordObject(wdDocuments);
}
}
}
The question is: how can I lock to prevent 2 users changing the active printer on the same time?