2017-03-13 88 views
0

我是C#初学者,想就如何解决下列问题的一些建议:串行端口和多线程问题

我愿不断从串口读取和数据存储在SQL数据库同时将其写入文本文件。

有没有什么办法可以连续从串口读取数据并在两个单独的线程中使用这些数据,而且它们也不在while循环中?

我为我的SQL代码:

public static void SQL_Logger(string data) 
{ 
    //Connect to database 
    PHINS_Connection = new SQLiteConnection("Data Source=PHINSDatabase.sqlite;Version=3;"); 
    PHINS_Connection.Open(); 
    SQLiteCommand command = new SQLiteCommand(sql, PHINS_Connection); //creates executing comman 
                     //Query for creating the table 
    //Execute the query 
    command.ExecuteNonQuery(); 
    if (data.Contains("Ambient")) 
    { 
     //Query for inserting a column into the table created above with the roll data 
     sql = "insert into PHINS_Data (valueType, value) values ('Ambient Temp'," + 199 + ")"; 

     //Create and execute the insert query 
     command = new SQLiteCommand(sql, PHINS_Connection); 
     command.ExecuteNonQuery(); 
    } 

而对于textLogger代码:

public static void textLogger(string text, string path) 
{ 
    using (StreamWriter writer = new StreamWriter(path, true)) 
    { 
     writer.WriteLine(text); 
    } 
} 

和主要程序:

class Program 
{ 
    static SerialPort newPort = new SerialPort("COM9", 9600); 

    static SQLiteConnection PHINS_Connection; 

    static string sql = "create table PHINS_Data (valueType varchar(20), value decimal(10, 3))"; // Creates table 

    static void Main(string[] args) 
    { 
     SQLiteConnection.CreateFile("PHINSDatabase.sqlite"); 

     string path = "PHINS-R-" + DateTime.Now.Ticks.ToString() + ".txt"; 
     using (FileStream fs = File.Create(path)) { } 

     newPort.Open(); 

     Thread myNewThread = new Thread(() => textLogger(data, path)); 
     Thread myNewThread2 = new Thread(() => SQL_Logger(data)); 

     while (true) 
     { 
      data = newPort.ReadLine(); 

      myNewThread.Start(); 
      myNewThread2.Start(); 
     } 

每次我做到这一点尝试每次循环执行时重新启动线程。是否有可能连续读取数据并将其传递给两个线程?

+0

你可以写一些DataAdapter的,这是在while循环,并提供了其他两个或多个应用程序 –

+2

是线程安全的方法。使用两个线程安全队列。读者将消息写入队列。线程将来自队列的消息出队并将它们写入其各自的位置。 TPL数据流具有许多可用于实现此功能的功能。 – spender

+0

好的谢谢。你有什么我可以在这里实现线程安全队列的例子吗?道歉,我是一个完整的初学者。 – Noj911

回答

-1

我会使用SerialPort.DataReceived事件将数据添加到某种全局队列中。而不是创建一个线程来处理全局队列。

private Queue<string> MyQueue = new Queue<string>(); 
    private object _lock = new object(); 

    public void Worker() 
    { 
     do 
     { 
      string val = ""; 
      lock (_lock) 
      { 
       if (MyQueue.Count > 0) 
       { 
        val = MyQueue.Dequeue(); 
       } 
      } 

      if (val == "") 
      { 
       System.Threading.Thread.Sleep(500); 
      } 

     } while (true); 
    } 

    public void Add(string rec) 
    { 
     lock (_lock) 
     { 
      MyQueue.Enqueue(rec); 
     } 
    } 

呼叫添加从SerialPort.DataReceived