我是C#的新手,遇到問題。我有一個表單,它運行一個接收來自串口的輸入的線程。但是,當窗口關閉時,線程繼續運行。我試圖覆蓋virtual void OnClosing(object sender, CancelEventArgs e)
,但MessageBox保持彈出狀態,這意味着線程仍在運行。我究竟做錯了什麼?哪個是最好的生命週期方法來覆蓋窗口關閉前進行清理?Windows Form OnClosing停止線程
DisplayForm.cs
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
namespace project
{
public partial class DisplayForm : Form
{
private Thread readThread;
private SerialPort port;
private bool running;
public DisplayForm(String portName)
{
InitializeComponent();
port = new SerialPort(portName);
port.Open();
readThread = new Thread(Read);
running = true;
readThread.Start();
}
public void Read()
{
while (running)
{
try
{
string message = port.ReadLine();
Console.Write(message);
MessageBox.Show(message);
}
catch (TimeoutException)
{
}
}
}
protected virtual void OnClosing(object sender, CancelEventArgs e)
{
running = false;
readThread.Join();
port.Close();
}
}
}
「這似乎不起作用」......爲什麼不呢?怎麼了?你在調試器中看到什麼? – SLaks 2012-03-23 00:53:51
調試器中沒有任何內容。 MessageBoxes保持彈出狀態,這意味着線程仍在運行 – 2012-03-23 00:54:36
它可能是積壓的消息嗎?如果你刪除MessageBox並觀看控制檯呢? – 2012-03-23 01:03:43