2011-04-18 2 views
2

BackgroundWorker을 사용하여 Form이 스레드 된 작은 응용 프로그램을 만들었으며 양식을 닫을 때 Program 클래스의 QuitApplication 함수를 호출하고 있습니다. CancelAsync가 작동하고 있습니까?

DoWork

은 다음과 같습니다

void Form1_FormClosed(object sender, FormClosedEventArgs e) 
{ 
    Program.instance.SetStatus("Closing down...", 0); 

    Program.QuitApplication(); 
} 

그래서 내가 원하는 것은 그 모든 것을 보장하는 것입니다 :

static void guiThread_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 

    while (true) 
    { 
     if (worker.CancellationPending == true) 
     { 
      e.Cancel = true; 
      break; 
     } 

     if (Program.instance.form != null) 
     { 
      Program.instance.form.UpdateStatus(Program.instance.statusText, Program.instance.statusProgress); 
     } 

     Thread.Sleep(GUI_THREAD_UPDATE_TIME); 
    } 
} 

그리고 난이 방법은 윈도우의 폐쇄에 부착 한 Form1 클래스에

창에서 X를 누르면 종료됩니다. 그러나, if(worker.CancellationPending == true) 결코 안타 ... 왜이 무엇입니까?

QuitApplication은 다음과 같습니다

public static void QuitApplication() 
{ 
    Program.instance.guiThread.CancelAsync(); 

    Application.Exit(); 
} 

그리고 그것을 감지하고 차단 할 수있는 기회를 스레드 임은 CancellationPending 속성을 설정하는 것입니다

+0

의 중복 가능성 [.NET :?를 BackgroundWorker에 취소를 기다리는 방법] (http://stackoverflow.com/questions/123661/net-how-to-wait-for-a -backgroundworker-to-cancel) – codingbadger

답변

3

CancelAsyncguiThread.WorkerSupportsCancellation = true를 사용하여,하지만 당신은 즉시 배경을주지 않고 응용 프로그램을 종료 하위. 백그라운드 스레드가 끝날 때까지 대기하도록 UI 코드를 변경해야합니다.

개인적으로 이런 앱을 작성하면 양식 닫기 버튼이 즉시 종료되는 대신 취소 버튼처럼 작동합니다. 최종 사용자에게는 훨씬 안전합니다. 예를 들면 :

private void abortButton_Click(object sender, EventArgs e) { 
    // I would normally prompt the user here for safety. 
    worker.CancelAsync(); 
} 

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { 
    if(worker.IsBusy) { 
     // If we are still processing, it's not very friendly to suddenly abort without warning. 
     // Convert it into a polite request instead. 
     abortButton.PerformClick(); 
     e.Cancel = true; 
    } 
} 
+0

QuitApplication에서 잠시 수행 할 수 있습니까 (guiThread.isBusy); Application.Exit 전에? 하지만, Application.Exit을 종료하면 모두 종료됩니까? – Jason94

+0

제이슨, 그 대답에 대한 배리의 질문 링크를보십시오. 내가 말하고 싶은 것은, 내가 제안한 것을 대신하여 이슈를 완전히 피하는 것이 사용자 친화적이라고 생각한다. –

+0

Form1이 어떻게 작업자에 대해 알게합니까? 또는 당신이 의미 했습니까 : if (Program.instance.worker.IsBusy)? – Jason94

관련 문제