Adding/Removing COM Ports from a ComboBox in C#
I am attempting to write a program that utilizes a ComboBox to display currently connected COM ports obtained from the following method:
System.IO.Ports.SerialPort.GetPortNames()
The idea is to initialize a thread that checks the currently available COM ports every second, and update the Comb开发者_如何学PythonoBox accordingly. Despite my best efforts, I can't get it to work.
The code to update the ComboBox's contents is the following:
private void Form1_Load(object sender, EventArgs e)
{
availPorts = new BindingList<String>();
Thread t = new Thread(new ThreadStart(update));
t.Start();
}
private void update()
{
this.comboBox1.DataSource = availPorts;
while (true)
{
Console.WriteLine("CHECK");
foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
{
if (!availPorts.Contains(port))
{
Console.WriteLine("FOUND");
availPorts.Add(port);
}
}
Thread.Sleep(1000);
}
}
I can see the console messages as the ports are found, however the ComboBox remains empty. Any help would be greatly appreciated.
Try modify code like this.
BindingList<String> availPorts = new BindingList<String>();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
private void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(update));
t.Start();
autoResetEvent.WaitOne();
this.comboBox1.DataSource = availPorts;
}
private void update()
{
//this.comboBox1.DataSource = availPorts;
while (true)
{
Console.WriteLine("CHECK");
foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
{
if (!availPorts.Contains(port))
{
Console.WriteLine("FOUND");
availPorts.Add(port);
}
}
autoResetEvent.Set();
}
}
The ComboBox is not being updated because the thread created to run the update method is attempting to update a visual control belonging to another thread. In most cases this would throw an error, however here it does not.
I solved this problem by first creating a method, separate from update, that only handles the addition of COM port names to the data source. Within this method is an if statement checking if an invoke is required:
private void addPort(String port)
{
if (this.InvokeRequired)
{
this.Invoke(new addPortDelegate(addPort), port);
}
else
{
availablePorts.Add(port);
Console.WriteLine("FOUND");
}
}
If an invoke is required, the method is called within the correct thread via a delegate:
private delegate void addPortDelegate(String s);
This causes the ComboBox to be updated as new COM ports are detected by the continuous execution of the update method. A similar method can be written to remove COM ports that have been disconnected from the system. Just don't forget to end the thread when the form closes or else it will spin infinitely.
精彩评论