3

我正在用 c# (mono) 编写一个程序来打印到财务打印机 (escpos),它工作正常。问题是当我打印时,程序会挂起,直到我拥有的缓冲区被清除。因此,正如您想象的那样,如果我打印几张图像,它会变得更大,因此会挂起一段时间。这是不可取的。我用两种方式测试过

一种方式

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);

并且这两种方法都不允许程序继续执行。示例:如果它开始打印并且纸张用完,它将一直挂起,直到打印机恢复打印,这是不正确的方式。

提前感谢您的时间和耐心。

4

1 回答 1

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.
}

这是一种方法。您应该阅读异步编程模型以了解其他选项,并选择最适合您需求的选项。

您还可以使用Task Parallel Library,这可能更合适。

于 2013-04-11T23:15:59.880 回答