2017-08-08 92 views
-2

我想在c#中創建循環緩衝區。 我有Arduino板發送大量數據 當在串口命令丟棄緩衝區中的一些數據將丟失。 在這種情況下,我需要爲我的數據提供循環緩衝來使它們流暢。在c#中的串行端口的循環緩衝區#

InputData = ComPort.ReadByte(); 
object firstByte = InputData; 

if (ComPort.IsOpen==true) 
{ 
    s = Convert.ToString(Convert.ToChar(firstByte)); 
    temp1 += s; 
    lock (firstByte) {  
    if (Convert.ToInt32(firstByte)== 13) 
    { 
     temp = temp1; 
     temp1 = "";     
     LstGetInfo.BeginInvoke(new Action(()=> 
     { 
      if (temp !=null) 
      { 
       LstGetInfo.Items.Add(temp); 

       if (LstGetInfo.Items.Count >= 100) 
       { 
        LstGetInfo.Items.Clear(); 
        // ComPort.DiscardInBuffer(); 
        //ComPort.DiscardOutBuffer(); 
       } 
       FileStream fs = new FileStream(filename, FileMode.Append); 
       var data = System.Text.Encoding.UTF8.GetBytes(String.Format("{0} {1}", temp, DateTime.Now.ToString("hh mm ss")) +"\r\n"); 
       fs.Write(data, 0, data.Length); 
       fs.Close(); 
      } 
     })); 
     LstGetInfo.BeginInvoke(new Action(() => 
     { 
      LstGetInfo.TopIndex = LstGetInfo.Items.Count - 1; 
     })); 
    } 
} 

這個問題的任何解決方案?

+3

要小心,它可能是最好的*不*命名在C#中的變量'var',因爲它也像這樣使用:'變種香蕉= TRUE; –

+0

另外,如果有人編輯您的代碼以使其可讀,不要丟棄他們的編輯,他們正在嘗試幫助 –

+1

我沒有看到歷史中丟棄的編輯。 OP向您的編輯添加了「和」字樣。 – Amy

回答

-2

嘗試以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 


namespace ConsoleApplication72 
{ 
    class Program 
    { 

     static string buffer = ""; 

     static void Main(string[] args) 
     { 

     } 

     static void AddToBuffer(byte[] rxData) 
     { 
      buffer += Encoding.UTF8.GetString(rxData); 
     } 
     static string ReadLine() 
     { 
      int returnIndex = buffer.IndexOf("\n"); 
      if (returnIndex >= 0) 
      { 
       string line = buffer.Substring(0, returnIndex); 
       buffer = buffer.Remove(0, returnIndex + 1); 
       return line; 
      } 
      else 
      { 
       return ""; 
      } 
     } 
    } 
} 
+0

你能解釋一下你的代碼嗎? –

+0

我想你的意思是'buffer = buffer.Remove(0,returnIndex + 1)' – Amy

+0

代碼是一個非常簡單的FIFO。將接收數據添加到FIFO結尾。刪除從fifo返回的一行數據。 – jdweng