'using await and Task.Result in c# [duplicate]
Hi I am having following web api code which is having multiple async and await methods as shown below
[HttpPost("test/id")]
public async Task TestWebMethod(int id)
{
bool TestA = await _Service.GetAsyncMethodA(id);
if (TestA)
{
bool TestB = await _Service.GetAsyncMethodB(id);
await _Service.GetAsyncMethodC(TestB);
}
}
public async Task<bool> GetAsyncMethodA(int id)
{
// do something
}
public async Task<bool> GetAsyncMethodB(int id)
{
// do something
}
If we want to use the result from the first async method to be passed to the second method this implementation will work? or should i use Result keyword as shown below?
public async Task TestWebMethod(int id)
{
bool TestA = _Service.GetAsyncMethodA(id).Result;
if (TestA)
{
bool TestB = await _Service.GetAsyncMethodB(id).Result;
await _Service.GetAsyncMethodB(TestB);
}
}
Which is the correct approach in the above scenario ? with await keyword or use the Result keyword? Please suggest.
Solution 1:[1]
you need to fix the code. You can not use await and .Result together. You have to use something one. It is much better to use await
public async Task TestWebMethod(int id)
{
bool testA = await _service.GetAsyncMethodA(id);
if (testA)
{
var testB = await _service.GetAsyncMethodB(id);
await _service.GetAsyncMethodB(testB);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
