如何使普通的 WebRequest 异步和等待? [英] How to make ordinary WebRequest async and awaitable?

查看:14
本文介绍了如何使普通的 WebRequest 异步和等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使以下代码异步且可等待.

I need to make the following code async and awaitable.

我需要从 Web 服务器获取大量数据,然后这些数据将用于填充我的应用程序中的 xaml 页面.

I need to get a lot of data from the web server, and then this data will be used to populate the xaml page in my application.

所以,我需要 DefLogin() 方法可以等待.

So, I need the DefLogin() method to be awaitable.

有可能吗?

public void DefLogin()
    {
        postData = "My Data To Post";
        var url = new Uri("Url To Post to", UriKind.Absolute);
        webRequest = WebRequest.Create(url);
        webRequest.Method = "POST";
        webRequest.ContentType = "text/xml";
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }

    public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
        Debug.WriteLine("Start BEGINGetResponse");
        webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    public void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response;
            response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            string Response = streamReader.ReadToEnd();
            streamResponse.Close();
            streamReader.Close();
            response.Close();
            if (Response == "")
            {
                //show some error msg to the user        
                Debug.WriteLine("ERROR");

            }
            else
            {
                //Your response will be available in "Response" 
                Debug.WriteLine(Response);
            }
        }
        catch (WebException)
        {
            //error    
        }
    }

我在 StackOverflow 上看到了这个问题:转换普通带有 Async 和 Await 的 Http Post Web 请求,但我无法正确理解答案.

I saw this question on StackOverflow: Converting ordinary Http Post web request with Async and Await, but I could not understand the answer properly.

请问有人可以帮忙吗?我真的很感激!

Please can anyone help? I would be really grateful!

推荐答案

您可以使用 TaskFactory.FromAsync将APM转换为TAP,制作了很多这样的小扩展方法:

You can use TaskFactory.FromAsync to convert APM to TAP, making a lot of tiny extension methods like this:

public static Task<Stream> GetRequestStreamAsync(this WebRequest request)
{
  return TaskFactory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
}

并对 WebRequest.GetResponse 和(如有必要)Stream.WriteStream.Flush 等执行相同的操作.

and do the same for WebRequest.GetResponse and (if necessary) Stream.Write, Stream.Flush, etc.

然后您可以使用 asyncawait 编写您的实际逻辑,无需任何回调:

Then you can write your actual logic using async and await without any callbacks:

public async Task DefLoginAsync()
{
    postData = "My Data To Post";
    var url = new Uri("Url To Post to", UriKind.Absolute);
    webRequest = WebRequest.Create(url);
    webRequest.Method = "POST";
    webRequest.ContentType = "text/xml";
    using (Stream postStream = await webRequest.GetRequestStreamAsync())
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        await postStream.WriteAsync(byteArray, 0, byteArray.Length);
        await postStream.FlushAsync();
    }
    try
    {
        string Response;
        using (var response = (HttpWebResponse)await webRequest.GetResponseAsync());
        using (Stream streamResponse = response.GetResponseStream())
        using (StreamReader streamReader = new StreamReader(streamResponse))
        {
            Response = await streamReader.ReadToEndAsync();
        }
        if (Response == "")
        {
            //show some error msg to the user        
            Debug.WriteLine("ERROR");

        }
        else
        {
            //Your response will be available in "Response" 
            Debug.WriteLine(Response);
        }
    }
    catch (WebException)
    {
        //error    
    }
}

这篇关于如何使普通的 WebRequest 异步和等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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