2011-09-07 3 views
3

와 내가 다운로더 파일파일 다운로드 BackgroundWorker에

private void btnTestDownload_Click(object sender, EventArgs e) 
{ 
backgroundWorker1.RunWorkerAsync(); 
} 

및 작동을 만들었습니다! 하지만

private void btnTestDownload_Click(object sender, EventArgs e) 
{ 
backgroundWorker1.CancelAsync(); 
} 

backgroundWorker dos not stop!

+0

을 처리하는 파일

WebClient Client = new WebClient(); public void TestStart() { //Handle the event for download complete Client.DownloadDataCompleted += Client_DownloadDataCompleted; //Start downloading file Client.DownloadDataAsync(new Uri("http://mywebsite.co.uk/myfile.txt")); } void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { //Remove handler as no longer needed Client.DownloadDataCompleted -= Client_DownloadDataCompleted; //Get the data of the file byte[] Data = e.Result; } public void TestCancel() { Client.CancelAsync(); Client.DownloadDataCompleted -= Client_DownloadDataCompleted; } 

을 다운로드하고,이 핸들 제거합니까? –

답변

1

배경 작업자의 목적에 대해 완전히 잘못된 생각이 들리는 것 같습니다. 취소 할 수있는 기능과 함께 비동기 적으로 단일 파일을 다운로드하려는 경우이 모든 기능이 WebClient 클래스에 내장되어 있습니다.

배경 작업자는 전체적으로 프로세서 집약적 인 장기 실행 작업용입니다. 예를 들어 다운로드 한 파일이 큰 텍스트 파일이고 텍스트 파일의 각 행을 구문 분석해야하는 경우 배경 작업자를 사용할 수 있습니다 (예 :

당신의 _worker_ 코드 파일

BackgroundWorker worker = new BackgroundWorker() { WorkerSupportsCancellation = true }; 

    //Take a stream reader (representation of a text file) and process it asyncronously 
    public void ProcessFile(StreamReader Reader) 
    { 
     worker.DoWork += worker_DoWork; 
     worker.RunWorkerAsync(Reader); 
    } 
    public void CancelProcessFile() 
    { 
     worker.CancelAsync(); 
    } 

    void worker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     //Get the reader passed as an argument 
     StreamReader Reader = e.Argument as StreamReader; 
     if (Reader != null) 
     { 
      //while not at the end of the file and cancellation not pending 
      while (Reader.Peek() != -1 && !((BackgroundWorker)sender).CancellationPending) 
      { 
       //Read the next line 
       var Line = Reader.ReadLine(); 
       //TODO: Process Line 
      } 
     } 
    } 
+0

WebClient는 당신이 사용하는 것에 따라 DownloadFileAsync와 DownloadStringAsync를 가지고있다. 이벤트 핸들러는 다르지만 동일한 취소 f}을 사용합니다. – ForbesLindesay

4

CancelAsync 작업자가 멈추지 않습니다. 수동으로해야합니다. 작업자 메소드 내에서 주기적으로 점검을해야하는지 여부를 알기 위해 CancellationPending 속성을 점검해야합니다.

그래서 기본적으로 DoWork 메서드 본문은 다음과 같이해야한다 : 당신이 당신의 작업자 방법 내에서 단지 자체는 완료하는 데 시간이 오래 걸리는 다른 방법을 호출하고 경우

foreach(var something in somethingelse) 
{ 
    if (worker.CancellationPending == true) { 
    e.Cancel = true; 
    return; 
    } 
    //do your work here 
} 

하는 것은 당신이이 없습니다 주기적으로 CancellationPending 변수를 확인할 가능성이 있으므로 스레드를 강제로 삭제하지 않고 명령을 수행하여 작업자를 중지시키는 것은 쉽지 않습니다.

+0

은 나에게 오류를 준다. (뭔가 무언가에 var가있다.) –

2

MSDN를 참조하십시오 : 당신이 CancelAsync를 호출 할 때, 당신의 노동자 방법의 실행을 중지하고 종료 에 기회가

. 작업자 코드는 주기적으로 CancellationPending 속성이 true로 설정되어 있는지 확인해야합니다.