2012-03-10 165 views
0

下面的代碼無法正常工作,不知何故,我可以從「已完成」方法的int值不了我的btn_Start_Click方法:打開文件完成

private void btn_Start_Click(object sender, EventArgs e) 
{ 
    int completedDownload = 0;  

    WebClient webClient = new WebClient(); 
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); 
    webClient.DownloadFileAsync(new Uri("http://somesite.com/file.jpg"), @"c:\file.jpg"); 

    if (Completed.completeDownload == 1) 
    { 
     //open the file code goes here. 
    } 

    //Rest of the code goes here. 
    //and here 
    //and here 
} 

private void Completed(object sender, AsyncCompletedEventArgs e) 
{ 
    completedDownload = 1; 
} 
+1

「異步」 的意思是 「以後發生」。將DownloadFileAsync調用後的所有代碼移至Completed方法。請注意,Completed由線程池線程調用,您需要使用Control.BeginInvoke()來運行更新UI的任何代碼。 – 2012-03-10 14:59:30

回答

2

從上WebClient.DownloadFileAsync功能的言論:

該文件是使用被 自動從線程池分配線程資源異步下載。要在文件可用時收到通知 ,請將事件處理程序添加到 DownloadFileCompleted事件。

MSDN Documentation

這似乎是一個更好的選擇,火的時候,該文件已完成將涉及使用事件處理程序的功能。下面是使用DownloadFileCompleted處理程序的一個示例:

// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt"); 
public static void DownLoadFileInBackground2 (string address) 
{ 
    WebClient client = new WebClient(); 
    Uri uri = new Uri(address); 

    // Specify that the DownloadFileCallback method gets called 
    // when the download completes. 
    client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2); 
    // Specify a progress notification handler. 
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback); 
    client.DownloadFileAsync (uri, "serverdata.txt"); 
} 

MSDN Documentation

1

已完成的處理程序異步執行。當你檢查這個int時,hanlder沒有設定保證值。如果您想在下載完成時執行某些操作,請在「完成」方法中執行此操作。

+0

「問題」是我想運行我的所有代碼在1方法,即「btn_Start_Click」,所以這不是一個真正的選擇在我的情況。 – naaitsab 2012-03-10 15:01:04