【发布时间】:2014-07-31 05:51:51
【问题描述】:
我正在使用 WebClient 在 Windows Phone 8.1 应用程序中从 Internet 下载一些东西。 下面是我在我的应用程序中使用的示例代码 - 我在其中调用下面的方法,但我的网络客户端没有等待完成读取操作并在 OpenReadAsync 调用后立即返回。
如何确保我的方法返回操作必须等到 OpenReadCompleted 事件完成? 我看到了多个类似的问题,但找不到解决方案。
MyCustomObject externalObj; // my custom object
private static void CheckNetworkFile()
{
try
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += (s, e) =>
{
externalObj = myReadWebclientResponse(e.Result); // my custom method to read the response
};
webClient.OpenReadAsync(new Uri("http://externalURl.com/sample.xml", UriKind.Absolute));
}
catch (Exception)
{
externalObj = null;
}
}
【问题讨论】:
-
制作方法
async。如果您不知道这意味着什么,请阅读 C# 中的async方法 -
感谢@Alxandr 的回复,我确实尝试过使用 async/await 但行为相同。 OpenReadCompleted 事件在方法返回调用后完成。
标签: c# windows-phone-8.1 async-await task-parallel-library webclient