내 코드에 문제가 있습니다. 메인 양식이있는 그래픽 응용 프로그램을 만드는 중입니다. 단추를 클릭하면 일부 파일을 내보내는 동안 진행률 막대를 표시하는 새 양식을 만듭니다. 내 문제는 어떻게 진행 파일 표시 줄을 사용하여 양식을 닫으려고 할 때 어떤 파일을 내보낼 지 끝나지 않기 때문에 시작됩니다.닫을 때 스레드에서 메소드 실행 중지
새 형식에서는 내보내기 진행률을 확인하고 진행률 표시 줄을 채우는 메서드를 실행합니다.이 메서드는 매초마다 실행됩니다. 내보내려면 새 스레드를 만들고이 스레드는 내보내기 메서드를 실행합니다.
내보내기가 완료되면 양식과 스레드가 올바르게 닫히지 만 양식을 닫아 작업을 강제 종료하면 내보내기가 끝날 때까지 또는 기본 양식을 닫을 때까지 내보내는 스레드가 멈추지 않습니다.
그래서 어떻게 그 스레드를 멈출 수 있습니까?
public Form3(File file, string output, string inputFile)
{
InitializeComponent();
this.file = file;
this.output = output;
this.inputFile = inputFile;
progressLabel.Location = new Point(textProgress.Right, progressLabel.Top);
thread = new Thread((ThreadStart)delegate { Exporter.ExportToFile(this.file, this.output, this.inputFile); });
thread.IsBackground = true;
thread.Start();
TimerControl();
}
private void TimerControl()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Tick += new EventHandler(GetProgress);
t.Interval = 1000; // in miliseconds
t.Start();
}
private void GetProgress(object sender, EventArgs myEventArgs)
{
int x = Exporter.GetProgress();
progressBar.Maximum = 100;
if (!Exporter.stop)
{
progressBar.Value = x;
progressLabel.Text = x.ToString() + "%";
}
else
{
this.Close();
}
}
이것을 올바르게하려면, 'Exporter.ExportToFile()'에 취소 지원을 추가해야한다. –
잔인하지만 다소 효과적 :'Closing' 이벤트 'thread.Abort()'를 호출하십시오 - 물론 다른 방법도 좋습니다. –
그건 끔찍한 충고입니다. ['절대로 Thread.Abort()를 호출하지 마십시오]] (http://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort). –