Getting a sonar issues actually it is logged as a blocker saying replace result with await.
var registerData = new
{
arg1 = "1",
DeviceId = "2"
};
var content = new StringContent(JsonConvert.SerializeObject(registerData), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("myapicall", content);
if (!response.IsSuccessStatusCode || response.Content == null)
{
return null;
}
**MyClass myClass = JsonConvert.DeserializeObject<myClass>(response.Content.ReadAsStringAsync().Result);**
return myClass;
The error message i recieve is "Replace this use of 'Task.Result' with 'await'.See Rule". Error is in the highlighted line Can someone help me to fix this issue
I think the error is pretty clear. You are calling ReadAsStringAsync()
but the instead of awaiting the resulting Task you just try to read the result which will block the current thread until the reading is complete.
What SonarQube is asking you to do is to await the task instead which is the correct way to handle async workloads.
MyClass myClass = JsonConvert.DeserializeObject<myClass>(await response.Content.ReadAsStringAsync());
return myClass;
Or to make it clearer
var json = await response.Content.ReadAsStringAsync();
MyClass myClass = JsonConvert.DeserializeObject<myClass>(json);
return myClass;