2013-04-11 27 views
4

我正在做一個程序在c#(單聲道)打印到財務打印機(escpos),它工作正常。問題是,當我打印時,程序掛起,直到我有的緩衝區被清除。所以,如你所想象的,如果我打印一些圖像,它會變得更大,所以它會暫停一段時間。這是不可取的。非阻塞io使用BinaryWriter寫入到usblp0

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

既不方法允許程序繼續執行。例如:如果它開始打印並且紙張已用完,則它將掛起,直到打印機恢復打印,這是不正確的。

在此先感謝您的時間和耐心。

+2

您必須提供對'BeginWrite'方法的回調,該方法將在寫入完成時調用。 – 2013-04-11 12:16:35

+1

爲什麼在直接寫入基礎流時使用'BinaryWriter'?爲什麼不只是'f = new FileStream(...)',然後調用'f.BeginWrite'? – 2013-04-11 14:43:17

+0

吉姆Mischel,我會得到什麼?我在方法一中做類似的程序。 outBuffer.BaseStream.BeginWrite – 2013-04-11 15:27:28

回答

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,這可能更適合。

+0

Iv查看單聲道的源代碼,我看到「超時不支持此流。」這意味着當打印機打開或其他任何東西時,我都沒有任何方法可以提醒您。 – 2013-04-15 10:55:36

+1

@CésarAraújo:那麼你可能想用'ThreadPool.RegisterWaitForSingleObject'來註冊一個等待和一個超時,然後用一個取消令牌調用'Stream.WriteAsync'來完成寫操作。如果等待信號超時,則可以取消打印操作。請參閱http://msdn.microsoft.com/en-us/library/hh137799.aspx。或者''Task'有一些超時功能。對此我不確定。 – 2013-04-15 13:53:57

+0

我找到了解決方案。開始一個線程並在線程中做一個超時工作看起來不錯。感謝所有的幫助。 – 2013-04-29 15:20:16