简体   繁体   English

如何非异步下载数据?

[英]How to download data non asynchronously?

I want to download data non asynchronously in a Windows Phone application. 我想在Windows Phone应用程序中异步下载数据。 I would make a downloader class, and have a simple method in it to download a string from a URL. 我将创建一个downloader类,并具有一个简单的方法来从URL下载字符串。 On other platforms, I would use: 在其他平台上,我将使用:

 public class TextDownloader
 {
      public string GetString(string url)
      {
           WebClient web = new WebClient();
           string s = web.DownloadString("http://www.google.com");
           return s;
      }
 }

It would work well: simple, minimal code. 它会很好地工作:简单,最少的代码。 However, the WebClient.DownloadString method is not available on Windows Phone 7, nor many WebRequest options. 但是,Windows Phone 7上不提供WebClient.DownloadString方法,也没有许多WebRequest选项。 Are there any alternative ways to download data non asynchronously in Windows Phone? 是否有其他方法可以非同步地在Windows Phone中下载数据? I would rather not have to create multiple events for download and error, just have a simple method return a value or throw an exception. 我宁愿不必为下载和错误创建多个事件,而只需使用一个简单的方法即可返回值或引发异常。

Indeed, you cannot use the synchronous model for downloads with WebClient out-of-the-box. 的确,您不能将同步模型用于开箱即用的WebClient下载。 This is by design, and given the nature of Windows Phone applications, you should follow this methodology. 这是设计使然,鉴于Windows Phone应用程序的性质,您应遵循此方法。

The solution to your problem - callbacks . 解决问题的方法- 回调 You can easily refactor your function to something like this: 您可以轻松地将函数重构为如下形式:

public void GetString(string url, Action<string> onCompletion = null)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += (s, e) =>
        {
            if (onCompletion != null)
                onCompletion(e.Result);
        };
    client.DownloadStringAsync(new Uri(url));
}

This makes it relatively easy to use and trigger an action when it is completed. 这使得它相对易于使用,并在完成时触发动作。 There is another way to do this as well, and that is - async/await . 还有另一种方法可以做到这一点,即-async / await You will need to install the Bcl.Async package through NuGet: 您将需要通过NuGet安装Bcl.Async软件包:

Install-Package Microsoft.Bcl.Async -Pre 

It would let you do this: 它可以让您做到这一点:

public async Task<string> DownloadString(string url)
{
    WebClient client = new WebClient();
    return await client.DownloadStringTaskAsync(url);
}

Still, though, it will be bound to the asynchronous model, just wrapped in a different manner and the thread will be waiting to get the string before returning it back to the caller. 尽管如此,它仍将绑定到异步模型,只是以不同的方式包装,线程将等待获取字符串,然后再将其返回给调用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM