2016-08-29 142 views
2

我正在使用WebClient.DownloadFileAsync()方法,並且想知道如何將參數傳遞給WebClient.DownloadFileCompleted事件(或任何其他事件),並在調用的方法中使用它。將參數傳遞給WebClient.DownloadFileCompleted事件

我的代碼:

public class MyClass 
{ 
    string downloadPath = "some_path"; 
    void DownloadFile() 
    { 
     int fileNameID = 10; 
     WebClient webClient = new WebClient(); 
     webClient.DownloadFileCompleted += DoSomethingOnFinish; 
     Uri uri = new Uri(downloadPath + "\" + fileNameID); 
     webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\" + fileNameID); 
    } 

    void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e) 
    { 
     //How can i use fileNameID's value here? 
    } 

} 

如何傳遞參數給DoSomethingOnFinish()

+0

我現在唯一能想到的唯一方法是,您可以將文件名保存在全局私有字段中並在其中訪問'DoSomethingOnFinish' –

+0

@ ChristophKn這是我原來的解決方案,但也許有些東西更優雅:)當處理幾次下載時,這變得凌亂 – mihaa123

回答

5

您可以使用webClient.QueryString.Add("FileName", YourFileNameID);添加額外信息。

然後訪問它在你的DoSomethingOnFinish功能,

使用string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["FileName"];接收文件名。

這是代碼應該是什麼樣子:

string downloadPath = "some_path"; 
void DownloadFile() 
{ 
    int fileNameID = 10; 
    WebClient webClient = new WebClient(); 
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish); 
    webClient.QueryString.Add("fileName", fileNameID.ToString()); 
    Uri uri = new Uri(downloadPath + "\\" + fileNameID); 
    webClient.DownloadFileAsync(uri,ApplicationSettings.GetBaseFilesPath +"\\" + fileNameID); 
} 

void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e) 
{ 
    //How can i use fileNameID's value here? 
    string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"]; 
} 

即使這應該工作,你應該使用統一的UnityWebRequest類。您可能還沒有聽說過它,但這應該是這樣的:

void DownloadFile(string url) 
{ 
    StartCoroutine(downloadFileCOR(url)); 
} 

IEnumerator downloadFileCOR(string url) 
{ 
    UnityWebRequest www = UnityWebRequest.Get(url); 

    yield return www.Send(); 
    if (www.isError) 
    { 
     Debug.Log(www.error); 
    } 
    else 
    { 
     Debug.Log("File Downloaded: " + www.downloadHandler.text); 

     // Or retrieve results as binary data 
     byte[] results = www.downloadHandler.data; 
    } 
} 
+0

感謝您的快速響應,現在將檢查您的解決方案。目標是在單獨的線程上實現下載。 UnityWebRequest是我可以在主線程之外使用的東西嗎? – mihaa123

+0

首先,我想讓你理解你的問題中的代碼不使用'Thread'。您正在使用與'Thread'不同的'Async'。雖然'Async'比'Thread'更容易使用。至於'UnityWebRequest',你不能在另一個線程中使用它。你不能在另一個線程中使用Unity的API。雖然,我的答案中的兩個代碼都是相同的,他們都使用「Async」。 – Programmer

+0

如果您想在另一個Thread中實際使用'WebClient',則必須將'DownloadFileAsync'更改爲'DownloadFile',然後從另一個'Thread'調用您的整個'DownloadFile()'函數。 – Programmer