要求是連續讀取硬件中的數據並將數據發送到上層的 進行進一步處理。異步調用機制設計c#
目前我使用同步機制。即 請求 - >等待 - >讀取--->發送進行處理。
do
{
int ix = iy;
iy = 0;
if(ix<1)
{
while (((ix = ReadSst(ref sBuffer)) < 1) && bProcessNotEnded == true)
{
if (ix < 0) // BT Error
{
eErr = CError.BUFF_KILL; //Throw error and exit
break;
}
Thread.Sleep(2);
iTimeOut += 2;
if (iTimeOut > TIMEOUT_2000)
{
eErr = CError.TIMEOUT_ERR;
objLogger.WriteLine("HW TIMED OUT");
break;
}
}
}
iBytesRead = ix;
if (iBytesRead <= 0)
{
eErr = CError.READ_ERR;
objLogger.WriteLine("READ ERROR");
break;
}
sReadMsg = sReadMsg + sBuffer;
if(sReadMsg.Length >0)
iEndPos = sReadMsg.IndexOf('\n',1);
else
iEndPos = -1;
if (sReadMsg.Length > 2)
{
if ((iEndPos == 0 && sReadMsg[0] == '\n') || (iEndPos > 0 && sReadMsg[sReadMsg.Length - 1] == '\n' && sReadMsg[sReadMsg.Length - 2] == '\r')) //finished
{
Thread.Sleep(50); // wait a short time to be sure there that there is no further input
if (sReadMsg.Length >= 3 && sReadMsg[sReadMsg.Length - 3] == 'a')
continue;
iy = ReadSst(ref sBuffer);
if (iy == 0)
{
bProcessNotEnded = false;
objLogger.WriteLine("bProcessNotEnded is made false, End of frame detected");
break;
}
else if (iy < 0)
{
eErr = CError.BUFF_KILL; // error
break;
}
}
}
} while (bProcessNotEnded);
ReadSst方法是一個調用硬件來請求數據。
從代碼中可以看出,當前邏輯循環並讀取,直到bProcessNotEnded標誌爲真。一旦在我收到的字符串緩衝區中檢測到幀的結尾,我將該標誌設置爲假,循環停止(硬件讀取也是如此)
現在我需要在代碼中實現一些並行性,提升性能我想學習以異步方式完成閱讀的方式來改進它。
任何人誰會幫助我改善這種現有的設計。
在此先感謝
這是太低級了。用一個內存流包裝它,你會有同步/異步操作。 – 2011-05-11 05:38:42
您好,您可能也想在http://codereview.stackexchange.com/上發佈這個 – Larry 2011-05-11 05:49:42