在执行函数之前,如何检查WebClient下载是否已完成?

时间:2013-07-31 13:38:14

标签: c# windows-phone webclient

我正在尝试从不同的URL获取JSON文件。在尝试执行其他操作之前,如何确保完全下载这两个文件。

我的代码看起来像这样:

WebClient Url1 = new WebClient();
Url1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url1_DownloadStringCompleted);
Url1.DownloadStringAsync(new Uri("http://example.com"));
WebClient Url2 = new WebClient();
Url2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url2_DownloadStringCompleted);
Url2.DownloadStringAsync(new Uri("http://anotherexample.com"));

DoSomethingWithJson();

void Url1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null) 
        return;
    json1 = JObject.Parse(e.Result);
}

void Url2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null) 
        return;
    json2 = JObject.Parse(e.Result);
}

现在,当我尝试在DoSomethingWithJson()内的MessageBox中显示它们时,json1和json2会返回null值,我假设这可能是因为它们还没有被完全下载。

1 个答案:

答案 0 :(得分:2)

DownloadStringAsync()方法在下载字符串之前返回,因为它是一个异步方法。如果将DoSomethingWithJson()方法移动到已完成的处理程序,则在请求完成后将调用它。您可能希望向DoSomethingWithJson()方法添加逻辑,以便只有在填充所需的所有变量时它才能正常工作(如果确实需要在开始执行任何其他操作之前填充所有这些变量)。

WebClient Url1 = new WebClient();
Url1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url1_DownloadStringCompleted);
Url1.DownloadStringAsync(new Uri("http://example.com"));
WebClient Url2 = new WebClient();
Url2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url2_DownloadStringCompleted);
Url2.DownloadStringAsync(new Uri("http://anotherexample.com"));
var json1Done = false;
var json2Done = false;


void Url1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null) 
        return;
    json1 = JObject.Parse(e.Result);
    json1Done = true;
    if(json1Done && json2Done)
    {
        DoSomethingWithJson();
    }
}

void Url2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null) 
        return;
    json2 = JObject.Parse(e.Result);
    json2Done = true;
    if(json1Done && json2Done)
    {
        DoSomethingWithJson();
    }
}

或者,如果您使用的是.Net 4.5,则可以使用新的async / await功能:

WebClient Url1 = new WebClient();
var json1Task = Url1.DownloadStringTaskAsync(new Uri("http://example.com"));
WebClient Url2 = new WebClient();
var json2Task = Url2.DownloadStringTaskAsync(new Uri("http://anotherexample.com"));

json1 = await json1Task;
json2 = await json2Task;

DoSomethingWithJson();