我正在尝试从不同的 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 都会返回空值,我假设这可能是因为它们尚未完全下载。