1. 程式人生 > 實用技巧 >你可能寫了個假非同步,並不能提高請求執行緒池的吞吐量

你可能寫了個假非同步,並不能提高請求執行緒池的吞吐量

不知道用什麼詞形容,就叫它假非同步吧。

寫非同步方法,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(); 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();
        return content;
    }
    catch (Exception ex)
    {
        LogUtil.Error(ex);
        return string.Empty;
    }
}
View Code

測試程式碼:

/// <summary>
/// 測試1
/// </summary>
private async void button1_Click(object sender, EventArgs e)
{
    //task是自己寫的獨立執行緒池,為了防止測試過程對CLR執行緒池和非同步執行緒池造成干擾
    _task.Run(() =>
    {
        Thread.Sleep(200);

        int workerThreads1, completionPortThreads1, workerThreads2, completionPortThreads2;
        ThreadPool.GetMaxThreads(out workerThreads1, out completionPortThreads1);
        ThreadPool.GetAvailableThreads(out workerThreads2, out completionPortThreads2);
        Log("假非同步 已使用輔助執行緒:" + (workerThreads1 - workerThreads2) + ", 已使用非同步執行緒:" + (completionPortThreads1 - completionPortThreads2));
    });

    string str = await GetDataAsync();
}

/// <summary>
/// 測試2 
/// </summary>
private async void button2_Click(object sender, EventArgs e)
{
    //task是自己寫的獨立執行緒池,為了防止測試過程對CLR執行緒池和非同步執行緒池造成干擾
    _task.Run(() =>
    {
        Thread.Sleep(200);

        int workerThreads1, completionPortThreads1, workerThreads2, completionPortThreads2;
        ThreadPool.GetMaxThreads(out workerThreads1, out completionPortThreads1);
        ThreadPool.GetAvailableThreads(out workerThreads2, out completionPortThreads2);
        Log("真非同步 已使用輔助執行緒:" + (workerThreads1 - workerThreads2) + ", 已使用非同步執行緒:" + (completionPortThreads1 - completionPortThreads2));
    });

    string str = await GetDataAsync2();
}

/// <summary>
/// 假非同步
/// </summary>
private async Task<string> GetDataAsync()
{
    return await Task.Run<string>(() =>
    {
        //介面耗時大約1秒
        return HttpUtil.HttpGet("http://localhost:8500/api/test/TestGet?val=1", null, null);
    });
}

/// <summary>
/// 真非同步
/// </summary>
/// <returns></returns>
private async Task<string> GetDataAsync2()
{
    //介面耗時大約1秒
    return await HttpUtil.HttpGetAsync("http://localhost:8500/api/test/TestGet?val=1", null, null);
}
View Code

測試截圖:

我想知道 WebRequest 類的 GetResponseAsync 方法是怎麼實現的,反正使用.NET提供的類,我是無法實現這樣的方法。

這篇隨筆如果有錯誤,請指正,我只是拋磚引玉,提出疑問或者說假設。