2012-03-23 3 views
1

저는 C#을 처음 사용하는데 문제가 있습니다. 직렬 포트에서 입력을받는 스레드를 실행하는 Form이 있습니다. 그러나 창이 닫히면 스레드는 계속 실행됩니다. 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(); 
     } 
    } 
} 
+0

"작동하지 않는 것 같습니다"... 왜 안 되니? 무슨 일이야? 디버거에서 무엇을 볼 수 있습니까? – SLaks

+0

디버거에 아무 것도 없습니다. MessageBoxes가 여전히 계속 스레드가 실행 중임을 의미합니다. –

+0

메시지의 백 로그가 될 수 있습니까? MessageBox를 제거하고 대신 콘솔을 보면 어떻게 될까요? –

답변

3

Join()이 아닌 Abort()을 사용해야합니다.

protected virtual void OnClosing(object sender, CancelEventArgs e) 
{ 
    running = false; 
    readThread.Abort(); 
    port.Close(); 
} 
0

OnClosing이나 OnClosed 이벤트 통화 시도는 자식 스레드 실행을보고 당신이 이미 가지고있는 다음 runThread을 코드 먼저 호출 port.close에 ... 그들 모두를 중단하고 Oncl에서 액세스 할 수 있습니다.