串列埠的非同步讀取和處理
string strAllChar = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
string buffer = ""; //儲存讀取到的條碼資料
Queue<string> qBarcode = new Queue<string>();//存放所有讀取的條碼資料佇列
/// <summary>
/// 讀取串列埠條碼資料
/// </summary>
private void ReadBarcode()
{
while (true)
{
if (!serialPort1.IsOpen) continue;
Thread.Sleep(1000);
try
{
buffer += serialPort1.ReadTo("\r\n");
Next:
if (!buffer.Contains("("))//“(開始說明是我的條碼資料資訊,‘)’結尾
{
buffer = "";
continue;
}
else
{
int iposleft = buffer.IndexOf("(") + 1;
if (!buffer.Contains(")"))
{//中包含"("說明本次沒有讀完,再讀後面的一段,直到讀取到”)“
buffer = buffer.Substring(iposleft - 1);
}
else
{
int iposright = buffer.IndexOf(")") - 1;
string tempnew = buffer.Substring(iposleft, iposright - iposleft + 1);
if (tempnew == "NoRead")//返回”(NoRead)“說明是沒有讀取到條碼 報警 提示
{
qBarcode.Enqueue(tempnew);
Stop();
tsbStart.Enabled = true;
tsbStop.Enabled = false;
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "條碼位數不正確!請檢查";
tBSN.Focus();
tBSN.SelectAll();
}
);
}
else if (tempnew.Length != 23)
{
//除 ”NoRead “之外的其它 !=23 位的條碼報警提示
Stop();
tsbStart.Enabled = true;
tsbStop.Enabled = false;
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "條碼位數不正確!請檢查";
tBSN.Focus();
tBSN.SelectAll();
}
);
}
else
{
bool isAllowChar = true;
for (int i = 0; i < tempnew.Length; i++)
{
if (strAllChar.Contains(tempnew[i].ToString()))
{
continue;
}
else
{
isAllowChar = false;
break;
}
}
if (!isAllowChar)
{
//資料中有非法字元,報警提示
qBarcode.Enqueue(tempnew);
Stop();
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "條碼中有無法識讀的字元!請檢查";
tBSN.Focus();
tBSN.SelectAll();
}
);
buffer = "";
continue;
}
else
{
//成功,將資料加入到佇列中
if (!qBarcode.Contains(tempnew))
{
qBarcode.Enqueue(tempnew);
}
tsbStart.Enabled = false;
tsbStop.Enabled = true;
sendLow();
}
}
WriteToFile(strSaveTxt, tempnew + " " + qBarcode.Count.ToString());
if (iposright + 2 > buffer.Length)
{
buffer = "";
continue;
}
else
{
//如果有多個"(("那麼 多次迴圈讀取 實際上應該不會發生
buffer = buffer.Substring(iposright + 2);
goto Next;
}
}
}
}
catch { }
}
}
/// <summary>
/// 處理讀取到的條碼資料
/// </summary>
private void SendToDBFromQueue()
{
while (true)
{
Thread.Sleep(500);
if (qBarcode.Count == 0) continue;
string strBarcode = qBarcode.Peek();
if (strBarcode.Length != 23)
{
//WriteToFile("D:\\dealwith.txt", qBarcode.Peek());
if(qBarcode.Count>0) qBarcode.Dequeue();
}
else
{
//條碼正確 開線
try
{
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
//WriteToFile("D:\\dealwith.txt", qBarcode.Peek());
//資料處理,儲存到遠端資料庫伺服器中
DealwithCommScan(strBarcode);
}
);
}
catch (Exception exc)
{
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
lbResult.Text = exc.Message;
}
);
}
}
}
}