mih*_*123 3 c# asynchronous unity-game-engine unity5
我正在使用该WebClient.DownloadFileAsync()方法,并想知道如何将参数传递给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?
}
}
Run Code Online (Sandbox Code Playgroud)
如何将参数传递给DoSomethingOnFinish()?
您可以使用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"];
}
Run Code Online (Sandbox Code Playgroud)
即使这应该工作,你应该使用Unity的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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3027 次 |
| 最近记录: |