앱을 닫을 때 앱이 여전히 작동하는 이유.
직렬 포트에서 데이터를 읽음으로써 발생하는 것 같습니다.
ComboBox에서 직렬 포트 번호를 선택합니다.
기능 직렬 포트의 데이터에 따라 WriteData 업데이트 확인란을 선택합니다.앱이 종료되지 않습니다.
// Choosing of communication port from ComboBox
private void comboBoxCommunication_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.Close();
}
try
{
ComboBoxItem cbi = (ComboBoxItem)comboBoxKomunikacia.SelectedItem;
portCommunication = cbi.Content.ToString();
serialPort.PortName = portCommunication;
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.BaudRate = 2400;
serialPort.Open();
serialPort.DiscardInBuffer();
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
// Close the window
private void Window_Closed(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
serialPort.Close();
}
}
// Data reading
private delegate void UpdateUiTextDelegate(char text);
private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (serialPort.IsOpen)
{
try
{
serialPort.DiscardInBuffer();
char c = (char)serialPort.ReadChar();
Dispatcher.Invoke(DispatcherPriority.Send,
new UpdateUiTextDelegate(WriteData), c);
}
catch(IOException ex)
{
MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
// Update of checkboxes
private void WriteData(char c) { ... }
다른 스레드가 있습니까? Closed 이벤트가 예상대로 실행되고 있는지 (디버거/로거) 확인할 수 있습니까? –
'serialPort' 객체가 처분 가능하다면 (그리고'SerialPort'가 있다고 생각합니다),이 코드에서 제대로 처분하지 않을 가능성이 있습니다. 변수의 범위가보다 잘 제어되고'using' 블록에 래핑 될 수 있도록 변수를 다시 구조화 할 수 있습니다. – David
@Henk Holterman - 다른 스레드 없음. 앱이 정상적으로 닫힙니다. 직렬 포트에서 데이터를 읽기 시작할 때만 제대로 닫히지 않습니다. –