简体   繁体   English

串口和多线程问题

[英]Serial port and multithreading issue

I am a beginner at C# and would like some advice on how to solve the following problem: 我是C#的初学者,想就如何解决以下问题提供一些建议:

I would like to continuously read from the serial port and store that data in an SQL database and write it to a text file simultaneously. 我想连续从串行端口读取数据并将其存储在SQL数据库中,然后同时将其写入文本文件。

Is there any way that you can continuously read from the serial port and use that data in two separate threads without them also being in the while loop? 有什么方法可以连续从串行端口读取并在两个单独的线程中使用该数据,而又不会使其处于while循环中?

My code for my SQL: 我的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();
    }

And the code for the textLogger: 以及textLogger的代码:

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

And the main program: 和主程序:

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

Every time I do this it tries to restart the thread every time the loop executes. 每次执行此操作时,每次循环执行时都会尝试重新启动线程。 Is it possible to continuously read the data and pass it to the two threads? 是否可以连续读取数据并将其传递给两个线程?

I would use the SerialPort.DataReceived event to add data to some kind of global queue. 我将使用SerialPort.DataReceived事件将数据添加到某种全局队列中。 And than create a thread to process the global queue. 然后创建一个线程来处理全局队列。

    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);
        }
    }

Call Add from SerialPort.DataReceived 从SerialPort.DataReceived调用Add

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

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