WebClient回调异步结果?

时间:2013-01-07 11:51:20

标签: c# webclient

我想编写一个处理我的WebClient-Tasks并返回其结果的类 问题是,异步下载不会让简单的return处理:

public void checkAvailability()
{
     WebClient wc = new WebClient();
     wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
     wc.UploadStringCompleted += wc_UploadStringCompleted;
     wc.UploadStringAsync(new Uri("http://random.php"), "?lookup=10");

     //return parsed content from wc_UploadStringCompleted
}

private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
     // do something
}

如何将它们组合在一起才能使其正常工作?

2 个答案:

答案 0 :(得分:3)

好的,使用Visual Studio 2012和.NET 4.5,可以更轻松地使用UploadStringTaskAsync()类中的System.Net.WebClient方法:

public async Task<string> CheckAvailability()
{
    var webClient = new WebClient();
    webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    var result = await webClient.UploadStringTaskAsync(new Uri("http://random.php"), "?lookup=10");
    return result;
}

该方法抛出的任何异常都会像常规的非异步方法一样中断您的应用程序流。请注意,无论你在哪里调用它来获得结果,你都需要await,所以:

var availability = await CheckAvailability();

在其他一些async标记方法中。

如果您不想使用此功能,则必须使用回调:

public void CheckAvailability(Action<Exception, string> callback)
{
    var webClient = new WebClient();
    webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    webClient.UploadStringCompleted += (s,e) => { 
                                                    if(e.Error != null)
                                                        callback(e.Error, string.Empty);
                                                    else
                                                        callback(null, e.Result);
                                                };
    wc.UploadStringAsync(new Uri("http://random.php"), "?lookup=10");
}

现在你必须传递返回void的函数并获取两个类型为Exceptionstring的参数,这些参数将在上传完成时执行,但你必须手动处理异常。

答案 1 :(得分:0)

使用UploadStringTaskAsync确实是一个更好的选择!

string data = "lookup=10";
string json = await WebClient.UploadStringTaskAsync(Uri, data);

帖子数据不需要“?”