[英]Nonblocking io using BinaryWriter to write to usblp0
我正在用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);
並且這兩種方法都不允許程序繼續執行。 示例:如果它開始打印並且紙張已用完,它將一直掛起,直到打印機恢復打印,這不是正確的方法。
提前感謝您的時間和耐心。
問題是你正在讓程序等待寫完成。 如果您希望它以異步方式發生,那么您需要提供一個在寫入完成時將調用的回調方法。 例如:
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.
}
這是一種方法。 您應該閱讀其他選項的異步編程模型 ,並選擇最適合您需求的選項。
您還可以使用任務並行庫 ,這可能更適合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.