我正在用c#(单声道)打印一个程序来打印到财务打印机(escpos),它运行正常。问题是,当我打印时,程序会挂起,直到清除了我的缓冲区。所以,正如你想象的那样,如果我打印几张图像,它会变大,所以它会挂起一段时间。这是不可取的。我已经用2种方式进行了测试
单程:
BinaryWriter outBuffer;
this.outBuffer = new BinaryWriter(new FileStream (this.portName,System.IO.FileMode.Open));
.... apend bytes to buffer...
IAsyncResult asyncResult = null;
asyncResult = outBuffer.BaseStream.BeginWrite(buffer,offset,count,null,null);
asyncResult.AsyncWaitHandle.WaitOne(100);
outBuffer.BaseStream.EndWrite(asyncResult); // Last step to the 'write'.
if (!asyncResult.IsCompleted) // Make sure the write really completed.
{
throw new IOException("Writte to printer failed.");
}
第二种方式:
BinaryWriter outBuffer;
this.outBuffer = new BinaryWriter(new FileStream (this.portName,System.IO.FileMode.Open));
.... apend bytes to buffer...
outBuffer.Write(buffer, 0, buffer.Length);
并且两种方法都不允许程序继续执行。示例:如果它开始打印并且纸张已用完,它将一直挂起,直到打印机恢复打印,这不是正确的方法。
提前感谢您的时间和耐心。
答案 0 :(得分:1)
问题是你正在让程序等待写完成。如果您希望它以异步方式发生,那么您需要提供一个在写入完成时将调用的回调方法。例如:
asyncResult = outBuffer.BaseStream.BeginWrite(buffer,offset,count,WriteCallback,outBuffer);
private void WriteCallback(IAsyncResult ar)
{
var buff = (BinaryWriter)ar.AsyncState;
// following will throw an exception if there was an error
var bytesWritten = buff.BaseStream.EndWrite(ar);
// do whatever you need to do to notify the program that the write completed.
}
这是一种方法。您应该阅读Asynchronous Programming Model了解其他选项,并选择最适合您需求的选项。
您也可以使用Task Parallel Library,这可能更合适。