-1

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.

A_developer
  • 115
  • 5
  • 22
  • 4
    Is this question related? [Await vs Task.Result in an Async Method](https://stackoverflow.com/questions/32239661/await-vs-task-result-in-an-async-method) – Theodor Zoulias Mar 10 '22 at 02:09

1 Answers1

2

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);
   }            
}
Serge
  • 40,935
  • 4
  • 18
  • 45