串口和多线程问题

时间:2017-03-13 13:33:19

标签: c# multithreading

我是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();
        }

每次执行此操作时,每次循环执行时都会尝试重新启动线程。是否可以连续读取数据并将其传递给两个线程?

1 个答案:

答案 0 :(得分:-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

调用Add