【问题标题】:Pass parameters to WebClient.DownloadFileCompleted event将参数传递给 WebClient.DownloadFileCompleted 事件
【发布时间】:2017-01-05 09:49:00
【问题描述】:

我正在使用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?
    }

}

如何将参数传递给DoSomethingOnFinish()

【问题讨论】:

  • 我现在能想到的唯一方法是,您可以将文件名保存在全局私有字段中并在DoSomethingOnFinish中访问它
  • @ChristophKn 那是我最初的解决方案,但我想也许有更优雅的东西:) 当处理多次下载时,这会变得很混乱

标签: c# asynchronous unity3d unity5


【解决方案1】:

您可以使用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"];
}

即使这应该有效,您也应该使用 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;
     }
 }

【讨论】:

  • 感谢您的快速回复,现在将检查您的解决方案。目标是在单独的线程上实现下载。 UnityWebRequest 是我可以在主线程之外使用的东西吗?
  • 首先,我想让你明白你问题中的代码没有使用Thread。您使用的 AsyncThread 不同。虽然,AsyncThread 更易于使用。至于UnityWebRequest,你不能在另一个线程中使用它。您不能在另一个线程中使用 Unity 的 API。虽然,我的答案中的两个代码都是等效的,它们都使用Async
  • 这是来自 MSDN:“文件是使用从线程池自动分配的线程资源异步下载的。”这不是说这个函数在内部使用了一个工作线程来下载文件吗? @程序员
  • 谢谢,我会阅读这个主题。关于我最初的问题-有什么方法可以将 ref 传递给带有 sender 对象的对象?类似于您建议的 int 类型的方式?
  • webClient.QueryString.Add( keyName, value ); 正是我需要的魔法。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-05-31
  • 2011-07-10
  • 1970-01-01
  • 2010-10-24
  • 2010-10-04
  • 2019-09-25
  • 2019-11-15
  • 2014-09-26
相关资源
最近更新 更多