C# async await異步編程簡要介紹

這裏簡要介紹async  await異步編程用法。

以HttpClient的PostAsync舉例,異步調用Http POST請求。

  public async Task<string> PostAsync(string url, string strJson)//post異步請求方法
        {
            try
            {
                HttpContent content = new StringContent(strJson);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                //由HttpClient發出異步Post請求
                HttpResponseMessage res = await client.PostAsync(url, content);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Thread.Sleep(1000);//線程睡眠1秒用於測試
                    string str = res.Content.ReadAsStringAsync().Result;
                    return str;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

編寫調用方式:

再編寫一個異步方法,用來獲取異步POST返回的信息,並進行一些操作。

        /// <summary>
        /// 再編寫一個異步方法,用來獲取異步POST返回的信息,並進行一些操作。
        /// </summary>
        /// <param name="url">POST請求地址</param>
        /// <param name="strJson">POST請求的json字符串參數</param>
        /// <returns></returns>
        private async Task<string> GetContentAsync(string url, string strJson)
        {
            HttpClientHelper cl = new HttpClientHelper();
            var content = await cl.PostAsync(url, strJson);
            textBox6.Text = content;
            return content;
        }

測試實例:

 private void button19_Click(object sender, EventArgs e)
        {
            InputText();
            jsonStuInfo stuInfo = new jsonStuInfo();
            stuInfo.sTID = this.sTID;
            stuInfo.nChildTID = this.nChildTID;
            string url = this.address + "Api_TestProc_Paper_GetPaperInfo";
            string strJson = JsonConvert.SerializeObject(stuInfo);
            var zipTeaInfo = GetContentAsync(url, strJson);
            textBox6.Text = zipTeaInfo.IsCompleted.ToString();
        }

此處返回信息經過加密,並非亂碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章