使用后台worker在windows服务中打印
本文关键字:服务 打印 windows 后台 worker | 更新日期: 2023-09-27 18:13:41
我正在开发一个Windows服务,它必须在网络打印机上打印一些标签。这里http://msdn.microsoft.com/en-us/library/5ekk3hse.aspx它说在Windows服务中使用System.Drawing.Printing类打印是不支持的(或者说不应该这样做)。
这个从Windows服务中使用c#打印html文档,没有打印对话框,似乎是解决方案,但他们说它需要。net Framework 4.0,我必须使用2.0(或者如果我真的,真的必须的话,我可以将其更改为3.5,但这样客户端将不得不升级,我想避免)。
我还读到要在网络打印机上从Windows服务打印,需要该服务的域帐户,我正在使用,所以这不是问题。
打印机的每个设置都将在。config文件中设置,我希望因此不会出现/需要的用户对话框。
我的问题:
我将能够直接从Windows服务中打印使用BackgroundWorker?或者我是否需要从我的服务内部调用另一个应用程序(例如控制台应用程序)并在那里进行打印(我在网上看到有些人使用这种解决方案,但我没有找到任何代码示例)
我也不擅长线程和后台工作,所以有人能给我一些例子,我怎么能做到这一点(我有请求异步打印来。我怎样才能打印出来而不丢失呢?后台工作器是最好的解决方案还是有更好的方法?
我还没有测试过从另一个线程打印,但这两个选项之一应该工作。你可能需要修改代码才能使用。net 2,因为我只使用3.5 Sp1或4。
假设您有一个Print
方法和一个Queue<ItemToPrint>
,其中ItemToPrint
是保存打印设置/信息的类
public Queue<ItemToPrint> PrintQueue = new Queue<ItemToPrint>();
private BackgroundWorker bgwPrintWatcher;
public void SetupBackgroundWorker()
{
bgwPrintWatcher = new BackgroundWorker();
bgwPrintWatcher.WorkerSupportsCancellation = true;
bgwPrintWatcher.ProgressChanged += new ProgressChangedEventHandler(bgwPrintWatcher_ProgressChanged);
bgwPrintWatcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwPrintWatcher_RunWorkerCompleted);
bgwPrintWatcher.DoWork += new DoWorkEventHandler(bgwPrintWatcher_DoWork);
bgwPrintWatcher.RunWorkerAsync();
}
void bgwPrintWatcher_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (!worker.CancellationPending)
{
// Prevent writing to queue while we are reading / editing it
lock (PrintQueue)
{
if (PrintQueue.Count > 0)
{
ItemToPrint item = PrintQueue.Dequeue();
// Two options here, you can either sent it back to the main thread to print
worker.ReportProgress(PrintQueue.Count + 1, item);
// or print from the background thread
Print(item);
}
}
}
}
private void Print(ItemToPrint item)
{
// Print it here
}
private void AddItemToPrint(ItemToPrint item)
{
lock (PrintQueue)
{
PrintQueue.Enqueue(item);
}
}
void bgwPrintWatcher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Anything here will run from the main / original thread
// PrintQueue will no longer be watched
}
void bgwPrintWatcher_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Anything here will run from the main / original thread
ItemToPrint item = e.UserState as ItemToPrint;
// e.ProgressPercentage holds the int value passed as the first param
Print(item);
}