如何等待WebClient的OpenReadAsync完成 [英] how to wait for webclient OpenReadAsync to complete

查看:1104
本文介绍了如何等待WebClient的OpenReadAsync完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Web客户端下载从互联网中的Windows Phone 8.1应用中的一些东西。
下面是示例code我用我的应用程序 - 我在哪里调用下面的方法,但我的Web客户端不等待完成读操作和OpenReadAsync电话后立即返回

我怎样才能确保我的方法的返回操作必须等到完成OpenReadCompleted事件?
我已经看到多个类似的问题,但无法找到一个解决方案。

  MyCustomObject externalObj; //我的自定义对象
私有静态无效CheckNetworkFile()
    {
        尝试
        {
            Web客户端Web客户端=新的WebClient();
            webClient.OpenReadCompleted + =(S,E)=>
            {
              externalObj = myReadWebclientResponse(e.Result); //我的自定义的方法来读取响应
            };            webClient.OpenReadAsync(新的URI(http://externalURl.com/sample.xml,UriKind.Absolute));
        }
        赶上(例外)
        {
          externalObj = NULL;
        }
    }


解决方案

我会建议你使用的 WebClient.OpenReadTaskAsync 用的 异步/的await 关键字引入在.NET 4.5来代替。您需要将异步关键字添加到您的方法,使其返回一个工作,这是明智结束你的方法与异步后缀:

  MyCustomObject externalObj;私有静态异步任务CheckNetworkFileAsync()
{
    尝试
    {
        Web客户端Web客户端=新的WebClient();        流流=等待webClient.OpenReadTaskAsync(新的URI(http://externalURl.com/sample.xml,UriKind.Absolute));
        externalObj = myReadWebclientResponse(流);
    }
    赶上(例外)
    {
      externalObj = NULL;
    }
}

编辑:

正如你所说, WebClient.OpenReadTaskAsync 不适用于WP8.1,所以让我们创建一个扩展方法所以这将是:

 公共静态类WebClientExtensions
{
    公共静态任务<流> OpenReadTaskAsync(这WebClient的客户,开放的URI)
    {
       VAR TCS =新TaskCompletionSource<流>();       OpenReadCompletedEventHandler openReadEventHandler = NULL;
       openReadEventHandler =(发件人,参数)=>
       {
          尝试
          {
             tcs.SetResult(args.Result);
          }
          赶上(例外五)
          {
             tcs.SetException(E);
          }
       };       client.OpenReadCompleted + = openReadEventHandler;
       client.OpenReadAsync(URI);       返回tcs.Task;
    }
}

现在你可以用它在你的 Web客户端

您可以在异步等待维基和伟大的阅读材料只需在搜索栏标签过滤。

I am using WebClient to download some stuff from internet in Windows Phone 8.1 app. Below is the sample code i am using in my app - where i am calling below method, but my webclient is not waiting to complete the read operation and returning immediately after OpenReadAsync call.

how can i make sure that my method return operation must wait till OpenReadCompleted event is completed? I have seen multiple similar questions, but couldn't find a solution.

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;
        }
    }

解决方案

I would advise you to use WebClient.OpenReadTaskAsync with a combination of the async/await keywords introduced in .NET 4.5 instead. You need to add the async keyword to your method, make it return a Task and it is advisable to end your method with the Async postfix:

MyCustomObject externalObj;

private static async Task CheckNetworkFileAsync()
{
    try
    {
        WebClient webClient = new WebClient();

        Stream stream = await webClient.OpenReadTaskAsync(new Uri("http://externalURl.com/sample.xml", UriKind.Absolute));                
        externalObj = myReadWebclientResponse(stream);
    }
    catch (Exception)
    {
      externalObj = null;
    }
}

Edit:

As you said, WebClient.OpenReadTaskAsync isn't available for WP8.1, So lets create an Extension Method so it will be:

public static class WebClientExtensions 
{
    public static Task<Stream> OpenReadTaskAsync(this WebClient client, Uri uri)
    {
       var tcs = new TaskCompletionSource<Stream>();

       OpenReadCompletedEventHandler openReadEventHandler = null;
       openReadEventHandler = (sender, args) => 
       {
          try 
          {
             tcs.SetResult(args.Result);
          } 
          catch (Exception e)
          {
             tcs.SetException(e);
          }
       };

       client.OpenReadCompleted += openReadEventHandler;
       client.OpenReadAsync(uri);

       return tcs.Task;
    }
}

Now you can use it on your WebClient.

You can find great reading material in the async-await wiki and by simply filtering by that tag in the search bar.

这篇关于如何等待WebClient的OpenReadAsync完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆