2012-06-13 2 views
4

이벤트 처리기를 WebClient의 DownloadProgressChanged 이벤트에 추가했지만 실행되지 않습니다. 파일은 성공적으로 다운로드되지만 진행 상황은 업데이트되지 않습니다.WebClient.DownloadProgressChanged가 호출되지 않습니다.

public class DownloadFile 
{ 
    private File file = null; 

    public DownloadFile(File file) 
    { 
     this.file = file; 
    } 

    public void startDownloadThread() 
    { 
     Console.WriteLine("Starting Download : "+file.URL); 

     var t = new Thread(() => DownloadThread(file)); 
     t.Start(); 
    } 

    public Action<string> action_error_downloadFailed = Console.WriteLine; 
    private void DownloadThread(File file) //Unnecessary argument but whatever ;D 
    { 
     try 
     { 
      string url = file.URL; 
      string savepath = file.DestinationDir + "\\" + file.Filename; 

      WebClient_B client = new WebClient_B(); 
      client.Proxy = null; //default to no proxy 
      client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); 
      client.DownloadFile(url, savepath); 

      Console.WriteLine("Download finished :" + file.Filename); 
     } 
     catch (Exception ex) 
     { 
      if (action_error_downloadFailed != null) 
       action_error_downloadFailed("Download failed :"+ex.Message); 
     } 
    } 

    private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
    { 
     try 
     { 
      if (file.TotalSize == 0) 
       file.TotalSize = (int)e.TotalBytesToReceive; 
      file.CurrentSize = (int)e.BytesReceived; 

      Form_DownloadManager.rebuildQueue(); 

      Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...", 
      (string)e.UserState, 
      e.BytesReceived, 
      e.TotalBytesToReceive, 
      e.ProgressPercentage); 
     } 
     catch (Exception ex) { Console.WriteLine("client_DownloadProgressChanged error : "+ex.Message); } 
    } 
} 

출력 : 내 서버가 다운로드 요청을 거절 유지하기 때문에 WebClient 클래스에 사용자 에이전트 + cookiecontainer 기능을 추가했기 때문에

Starting Download : http://x.x.x/y/z.zip 
'projectname.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 
The thread '<No Name>' (0x3b8c) has exited with code 0 (0x0). 
Download finished :z.zip 

내가 WebClient_B을 사용하고 있습니다. 이벤트는 결코 '표준'WebClient 클래스로 해고 된 적이 없습니다. 그래서 그게 문제가되어서는 안됩니다. 그러나 어쨌든; link to class

답변

8
client.DownloadFile(url, savepath); 

는 현재 당신이 차단, 동기 버전을 사용하여 파일을 다운로드 비동기 버전을 사용해야합니다. WebClient.DownloadProgressChanged에 대한 msdn docs에서

: 비동기 다운로드 작업이 성공적으로 데이터의 일부 또는 전부를 를 전송하는 경우

발생합니다. 귀하의 경우에는

될 것이라고 : 당신의 방법은 직접 결과를 반환하지 않기 때문에

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); 
client.DownloadFileAsync (url, savepath); 

는이 리팩토링은 문제가주의하지 않아야 다운로드가 가장 가능성이 완료되지 않았 음을 불구하고 메서드가 호출자에게 반환 될 때까지

+1

설명이 방법에 의존 할 수 업데이트하는 동안, 동 기적으로 웹 클라이언트를 사용하려면'DownloadProgressChanged'와'DownloadFileCompleted' 핸들러는 모두라는 스레드를 실행 'DownloadDataAsync' (테스트 당). –

5

가 진행을 얻는 것은 당신이 여기

http://alexfeinberg.wordpress.com/2014/09/14/how-to-use-net-webclient-synchronously-and-still-receive-progress-updates/

public void DownloadFile(Uri uri, string desintaion) 
{ 
    using(var wc = new WebClient()) 
    { 
    wc.DownloadProgressChanged += HandleDownloadProgress; 
    wc.DownloadFileCOmpleted += HandleDownloadComplete; 

    var syncObj = new Object(); 
    lock(syncObject) 
    { 
     wc.DownloadFileAsync(sourceUri, destination, syncObject); 
     //This would block the thread until download completes 
     Monitor.Wait(syncObject); 
    } 
    } 

    //Do more stuff after download was complete 
} 

public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs args) 
{ 
    lock(e.UserState) 
    { 
     //releases blocked thread 
     Monitor.Pulse(e.UserState); 
    } 
} 


public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args) 
{ 
    //Process progress updates here 
} 
+0

잠금을위한 param이 syncObj를 의미합니까? –

관련 문제