简体   繁体   English

非阻塞io使用BinaryWriter写入usblp0

[英]Nonblocking io using BinaryWriter to write to usblp0

I'm doing a program in c# (mono) to print to a fiscal printer (escpos) and it works okay. 我正在用c#(mono)编写程序来打印到财务打印机(escpos),它运行正常。 The problem is that when I print, the program hangs until the buffer I have is cleared. 问题是,当我打印时,程序会挂起,直到清除了我的缓冲区。 So, as you imagine if I print a couple of images it gets bigger and so it hangs for a while. 所以,正如你想象的那样,如果我打印几张图像,它会变大,所以它会挂起一段时间。 This is not desirable. 这是不可取的。 I have tested in 2 ways 我已经通过两种方式测试过

One way : 一种方式

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.");             
}

second Way : 第二种方式

BinaryWriter outBuffer;
this.outBuffer = new BinaryWriter(new  FileStream (this.portName,System.IO.FileMode.Open));
.... apend bytes to buffer...
outBuffer.Write(buffer, 0, buffer.Length);

and neither method is allowing the program to continue the execution. 并且这两种方法都不允许程序继续执行。 Example: if it starts to print and paper is out it will hang until the printer resumes printing which is not the right way. 示例:如果它开始打印并且纸张已用完,它将一直挂起,直到打印机恢复打印,这不是正确的方法。

Thanks in advance for your time and patience. 提前感谢您的时间和耐心。

The problem is that you're making the program wait for the write to complete. 问题是你正在让程序等待写完成。 If you want it to happen asynchronously, then you need to provide a callback method that will be called when the write is done. 如果您希望它以异步方式发生,那么您需要提供一个在写入完成时将调用的回调方法。 For example: 例如:

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

That's one way to do it. 这是一种方法。 You should read up on the Asynchronous Programming Model for other options, and pick the one that best suits your needs. 您应该阅读其他选项的异步编程模型 ,并选择最适合您需求的选项。

You can also use the Task Parallel Library , which might be a better fit. 您还可以使用任务并行库 ,这可能更适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM