繁体   English   中英

串口和多线程问题

[英]Serial port and multithreading issue

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

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

我将使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM