不知道用什么词形容,就叫它假异步吧。

写异步方法,async 和 await 要一路写到底,否则就是假异步,并不能提高请求线程池的吞吐量。

真正的异步,我的理解是这样的:比如调用一个查询接口,在当前线程,把SQL扔给数据库,当前线程释放,去干别的事情,数据库查询完了,通知我,我再在另一个线程里(也可能是刚才释放的那个线程,也可能不是)拿查询结果,返回给客户端,数据库查询比较耗时,数据库查询的时候,对线程是0占用。
 
HttpUtil.HttpGet方法:
/// <summary>
/// HttpGet
/// </summary>
/// <param name="url">url路径名称</param>
/// <param name="cookie">cookie</param>
public static string HttpGet(string url, CookieContainer cookie = null, WebHeaderCollection headers = null)
{
    try
    {
        // 设置参数
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.CookieContainer = cookie;
        request.Method = "GET";
        request.ContentType = "text/plain;charset=utf-8";

        if (headers != null)
        {
            foreach (string key in headers.Keys)
            {
                request.Headers.Add(key, headers[key]);
            }
        }

        //发送请求并获取相应回应数据
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //直到request.GetResponse()程序才开始向目标网页发送Post请求
        Stream instream = response.GetResponseStream();
        StreamReader sr = new StreamReader(instream, Encoding.UTF8);
        //返回结果网页(html)代码
        string content = sr.ReadToEnd();
        instream.Close();
        return content;
    }
    catch (Exception ex)
    {
        LogUtil.Error(ex);
        return string.Empty;
    }
}
View Code

HttpUtil.HttpGetAsync方法:

/// <summary>
/// HttpGetAsync
/// </summary>
/// <param name="url">url路径名称</param>
/// <param name="cookie">cookie</param>
public static async Task<string> HttpGetAsync(string url, CookieContainer cookie = null, WebHeaderCollection headers = null)
{
    try
    {
        // 设置参数
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.CookieContainer = cookie;
        request.Method = "GET";
        request.ContentType = "text/plain;charset=utf-8";

        if (headers != null)
        {
            foreach (string key in headers.Keys)
            {
                request.Headers.Add(key, headers[key]);
            }
        }

        //发送请求并获取相应回应数据
        HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
        //直到request.GetResponse()程序才开始向目标网页发送Post请求
        Stream instream = response.GetResponseStream();
        StreamReader sr = new StreamReader(instream, Encoding.UTF8);
        //返回结果网页(html)代码
        string content = sr.ReadToEnd();
        instream.Close();
        return content;
    }
    catch (Exception ex)
    {
        LogUtil.Error(ex);
        return string.Empty;
    }
}
View Code

测试代码:

相关文章:

  • 2022-12-23
  • 2021-10-28
  • 2021-09-28
  • 2022-01-17
  • 2022-01-10
  • 2022-02-06
  • 2022-12-23
猜你喜欢
  • 2021-08-24
  • 2021-11-09
  • 2021-07-15
  • 2021-09-04
  • 2021-12-06
  • 2021-09-20
  • 2021-08-30
相关资源
相似解决方案