Here I'm checking for propertie if it is Migrated or In-Progress, If In-Progress then I do not want to wait for Web Response
message from supplied URL
so HttpPost
method should run in Background
and calling method
should perform its task simultaneously.
To acheive this functionality I used async
and await
in below methods.
Below is the method to Post and Get XML
Response back from URL:
public static async Task<string> HttpPost(string url, string message, bool ignoreResponse = false)
{
string lcPostData = null;
string _XmlResponse = string.Empty;
try
{
using (var client = new HttpClient())
{
var httpContent = new StringContent(message, Encoding.UTF8, "application/xml");
var SupplierLinkUri = new Uri(url);
if (!ignoreResponse)
{
var httpResponseMessage = await client.PostAsync(SupplierLinkUri, httpContent);
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
_XmlResponse = httpResponseMessage.Content.ReadAsStringAsync().Result;
}
else if (ignoreResponse && !(isReservation(message))) //message.Contains("Reservation"))
{
/* I want below lines of code to run asynchronously (i.e. Run in background) So I used Task & await but it fails*/
Task<HttpResponseMessage> httpPostTask = client.PostAsync(SupplierLinkUri, httpContent);
HttpResponseMessage asyncPost = await httpPostTask;
}
}
}
catch (Exception e)
{
}
return _XmlResponse;
}
The above method IS running without errors but I want to know whether this is a right approach to use async
and await
in C#,
Should I need to modify my code anywhere or it is correct as per mentioned requirements?
await
in else-if
part is not working. As per documentation this should run asynchronously
i.e. in background but currently it is not.
Can anyone please check and suggest what is wrong in the code?
Is their any better way to achieve this?
Appreciate any suggestions and Ideas! Thanks for the help!