-1
我在寫一個C#程序,它將同時從多個串行端口讀取數據並將該數據記錄到文件中。每個端口都有它自己的專用文件來寫入。將多個串行端口同時記錄到多個文件
我能夠用一個端口成功創建一個類,但是當我嘗試使用兩個端口執行操作時,只有第二個打開的端口有任何寫入該文件的數據。
下面是我寫來處理數據從串口接收到的事件,並寫入到文件類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Ports;
namespace Shell
{
public class Shell
{
private string port_name;
static SerialPort port;
static FileStream fs;
static StreamWriter stream;
/*------------------------------------------------------
Constructors can be added as needed to take
additional inputs for more flexibility.
------------------------------------------------------*/
public Shell(string name)
{
port = new SerialPort();
port_name = name;
port.PortName = name;
port.BaudRate = 115200;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.Encoding = Encoding.UTF8;
}
/*------------------------------------------------------
Close the serial port and file.
------------------------------------------------------*/
public void close()
{
if (port.IsOpen)
{
port.DataReceived -= port_DataReceived;
port.Close();
stream.Dispose();
fs.Close();
}
}
/*------------------------------------------------------
Add the serial data received handler, open the file to
log to, and open the serial port.
------------------------------------------------------*/
public void open(string path)
{
if (!port.IsOpen)
{
fs = File.Open(path, FileMode.Create, FileAccess.ReadWrite);
stream = new StreamWriter(fs);
stream.AutoFlush = true;
stream.WriteLine("Start");
port.DataReceived += port_DataReceived;
port.Open();
}
}
/*------------------------------------------------------
Handler for the serial data events.
------------------------------------------------------*/
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = port.ReadExisting();
if (!string.IsNullOrEmpty(data))
{
stream.Write(data);
}
}
}
}
這裏是從簡單的形式我用來打開和關閉的代碼連接:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace shell_log_test
{
public partial class Form1 : Form
{
private Shell.Shell port1;
private Shell.Shell port2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
port2 = new Shell.Shell("COM5");
port2.open("port2.log");
port1 = new Shell.Shell("COM12");
port1.open("port1.log");
}
private void button2_Click(object sender, EventArgs e)
{
port1.close();
port2.close();
}
}
}
預先感謝您的幫助。
不要使用例如項目靜態字段。 –
是的,這是正確的,你將留下最近更新的端口和Streamwriter,因爲它們都是靜態的,它們每個類創建一個,而不是每個實例一個。 – Marshal
感謝您的快速回復。這改正了這個問題。 –