Service warm-up client using Async-Await
1.
Create an async method with HttpClient.
(For example, HttpGet & HttpPost)
public async Task<HttpStatusCode> Get(String apiUrl)
{
HttpClient httpClient = this.CreateHttpClient(apiUrl);
try
{
//GetAsync
HttpResponseMessage resp =
httpClient.GetAsync(apiUrl).Result;
//Throw an Exception when getting an
error Status Code
//resp.EnsureSuccessStatusCode();
return
resp.StatusCode;
}
catch (Exception ex){ return HttpStatusCode.NotFound; }
finally{
httpClient.Dispose();}
}
|
public async Task<HttpStatusCode> Post(String apiUrl)
{
HttpClient httpClient = this.CreateHttpClient(apiUrl);
try
{
//Create JSon
IcashMsg icashMsg = new IcashMsg();
//PostAsJsonAsync
HttpResponseMessage resp =
httpClient.PostAsJsonAsync(apiUrl, icashMsg).Result;
//Throw an Exception when getting an
error Status Code
//resp.EnsureSuccessStatusCode();
return resp.StatusCode;
}
catch (Exception ex){ return HttpStatusCode.NotFound; }
finally{
httpClient.Dispose();}
}
|
2.
The async sub-method await the HttpGet/HttpPost
method above, and then do the logical codes.
public async void ChkWebapi(ConnInfo connInfo)
{
using (WebApiConn wsConn = new WebApiConn())
{
// Response HttpStatusCode
HttpStatusCode peekStsCode = new HttpStatusCode();
peekStsCode = await wsConn.Get(connInfo.IP);
// peekStsCode = await wsConn.Post(connInfo.IP);
// logical/other codes here
}
}
|
3.
Since we finished the
async-await method, we can use some concurrent codes to test it.
//Get Urls
List<icasH.ApConsole.ApLib.ConnInfo>
connInfoList4Get = … ;
Parallel.ForEach(connInfoList4Get, conn =>
{
using (Conn Conns = new Conn())
{
Conns.ChkWebapi(conn);
}
});
|
4.
Reference
Best Practices in Asynchronous Programming
Best Practices in Asynchronous Programming
沒有留言:
張貼留言