.NET:向WebClient的UploadStringCompletedEventHandler提交用户定义标记的最佳方法是什么

时间:2016-08-27 15:35:40

标签: c# .net webclient

...如果我想重用处理程序,那么多个同时服务器响应可以被上下文化吗?

    var fileDownload1 = new WebClient();
    string myPostData1 = ...;
    string tag1 = "download1";   // <-- where do I put it?
    fileDownload1.UploadStringCompleted += new UploadStringCompletedEventHandler(OnFileDonwloadRequestCompleted);
    fileDownload1.UploadStringAsync(new Uri("http://www.somewhereinthe.net"), httpverb, myPostData1);

    ....

    var fileDownload2 = new WebClient();
    string myPostData2 = ...;
    string tag2 = "download2";   // <-- where do I put it?
    fileDownload2.UploadStringCompleted += new UploadStringCompletedEventHandler(OnFileDonwloadRequestCompleted);
    fileDownload2.UploadStringAsync(new Uri("http://www.somewhereinthe.net"), httpverb, myPostData2);

    ....

void OnFileDonwloadRequestCompleted(object sender, UploadStringCompletedEventArgs e)
{
    string tag = ???? ;   // <-- where can I get it?
    switch (tag)
    {
    case "download1": 
        ...
        break;
    case "download2":
        ...
        break;
    }
}

1 个答案:

答案 0 :(得分:2)

以下是如何确定哪个上传调用触发了您的回调函数:

UploadStringAsync方法调用中使用带有第四个参数object userToken的重载:

 fileDownload1.UploadStringAsync(new Uri("http://www.somewhereinthe.net"), 
                                                     httpverb, myPostData1, "download1");

并在OnFileDonwloadRequestCompleted方法中使用UserState属性来获取该值:

string tag = (string)e.UserState;