关闭表单在迭代端口时需要时间

时间:2017-02-24 09:59:52

标签: c# winforms performance serial-port

有循环遍历所有端口以连接特定端口。

但同时如果窗体关闭则需要时间,当我暂停并看到它停止时,调试点位于serialport.open()的声明中。

因此,当应用程序请求打开端口并同时关闭表单时,它会挂起一段时间,如果有超过6或7个端口,则需要更多时间。

示例代码:

string[] portNames = SerialPort.GetPortNames();

int detectPortCount = portNames.Length;

for (int i = 0; i < detectPortCount; i++)
{
    SerialPort discoveryPort = new SerialPort();
    discoveryPort.WriteTimeout = discoveryPort.ReadTimeout = 2000;

        try
        {
            discoveryPort.PortName = portNames[i];
            try
            {
                if (!discoveryPort.IsOpen) discoveryPort.Open();
            }
            catch (UnauthorizedAccessException uex)
            {
            }
        }
}

1 个答案:

答案 0 :(得分:0)

答案简短:

您无法取消port.Open()方法,但您可以将其设置为立即关闭。

正如@MongZhu建议您可以并行检查端口:

// Not inside the GUI Thread!
ConcurrentDictionary<string, SerialPort> ports = new ConcurrentDictionary<string, SerialPort>();

Parallel.ForEach(SerialPort.GetPortNames(), (currentPort) => 
{
    SerialPort discoveryPort = new SerialPort();
    discoveryPort.WriteTimeout = discoveryPort.ReadTimeout = 2000;

    try
    {
        discoveryPort.PortName = currentPort;
        try
        {
            if (!discoveryPort.IsOpen) discoveryPort.Open();
            // do something to check if it's the right port here.
            if(itIsTheRightPort) {
                ports.TryAdd(currentPort, discoveryPort);
            }
        }
        catch (UnauthorizedAccessException uex)
        {
        }
    }
});

除此之外,您可以在关闭之前始终Hide()表单:

public void OnClose(object sender, EventArgs e) 
{
    Form.Hide();
    WaitForAllTasksAndThreadsToFinishNiceAndClean();
    Close();
}