You're creating a series of
Task
objects, but never waiting for them to complete. The calling method will return before the work has finished. And if any of the tasks fails, it could end up taking down your entire process with an "unobserved exception" error.
You should make the
FindSessionAndInitiateCall
method
async
, and have it return a
Task
. You will then be able to wait for all of the child tasks to complete, and the caller will be able to wait for the work to finish.
You might also find it easier to use the
HttpClient[
^] class instead of the raw
WebRequest
class;
HttpClient
was designed to be
async
-friendly from the start, whereas the task-returning methods on the
WebRequest
were added long after its creation.
Your code also needs to set the command's connection property, and open the connection before trying to execute the command.
public async Task FindSessionAndInitiateCall(CancellationToken cancellationToken = default(CancellationToken))
{
List<Task> tasks = new List<Task>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("sp_FindSessionsToConnect", con))
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Task<string> request = CreateRequest(
dr.Field<string>("ManagerMob"),
dr.Field<string>("EmployeeMob"),
dr.Field<string>("SessionDuration"),
dr.Field<string>("SlotId"),
cancellationToken);
tasks.Add(request);
}
}
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private static readonly HttpClient Http = new HttpClient();
private async Task<string> CreateRequest(string ManagerMob, string EmployeeMob, string SessionDuration, string SlotId, CancellationToken cancellationToken)
{
const string URL = "*******************";
var parameters = new Dictionary<string, string>
{
["ManagerMob"] = ManagerMob,
["EmployeeMob"] = EmployeeMob,
["SessionDuration"] = SessionDuration,
["SlotId"] = SlotId,
};
var content = new FormUrlEncodedContent(parameters);
var response = await Http.PostAsync(URL, content, cancellationToken);
if (!response.IsSuccessStatusCode)
{
return string.Format("{0}: {1}", response.StatusCode, response.ReasonPhrase);
}
string objText = await response.Content.ReadAsStringAsync(cancellationToken);
var root = JObject.Parse(objText);
return root["msg"].ToString();
}
You're using HttpClient wrong and it is destabilizing your software | ASP.NET Monsters[^]