将AsyncCallback转换为可等待的任务

时间:2015-02-15 14:02:35

标签: c# windows-phone-8.1

我正在尝试实现给定网址的下载。顺便说一句,我的代码是:

private string url;
private StorageFile outputFile;

public void download()
{
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);
    request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
}
public async void playResponseAsync(IAsyncResult asyncResult)
{
    //Declaration of variables
    HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

    try
    {

        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
        {
            byte[] buffer = new byte[1024];

            using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outputStream = writeStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        using (Stream input = webResponse.GetResponseStream())
                        {
                            var totalSize = 0;
                            for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                            {
                                dataWriter.WriteBytes(buffer);
                                totalSize += size;    //get the progress of download
                            }
                            await dataWriter.StoreAsync();
                            await outputStream.FlushAsync();
                            dataWriter.DetachStream();
                        }
                    }
                }
            }
            Debug.WriteLine("Finished");
        }
    }
    catch
    {

    }
}
}

我希望我的下载方法具有以下签名

Task<bool> download();

(如果下载成功则返回true,否则返回false)

使其成为一项令人期待的任务。但我不掌握C#并且不知道该怎么做。你能救我吗?

由于

1 个答案:

答案 0 :(得分:2)

Task.Factory.FromAsync用于简化旧异步模式的使用

public async Task<bool> download()
{
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);
    HttpWebResponse webResponse = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, request);

    try
    {
        using (webResponse)
        {
            byte[] buffer = new byte[1024];

            using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outputStream = writeStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        using (Stream input = webResponse.GetResponseStream())
                        {
                            var totalSize = 0;
                            for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                            {
                                dataWriter.WriteBytes(buffer);
                                totalSize += size;    //get the progress of download
                            }
                            await dataWriter.StoreAsync();
                            await outputStream.FlushAsync();
                            dataWriter.DetachStream();
                        }
                    }
                }
            }
            Debug.WriteLine("Finished");
        }
    }
    catch
    {
        return false;
    }
}
return true;
}

但我会按建议使用较新的HttpClient