0

I came across this question on a test, and I'm stuck between two answers. Which would you consider correct and why? Is it possible that both are acceptable?

What have I read so far. Task is already asynchronous, so there would be no need to declare async again, A is correct. The return from A is not a string, but a Task, so B is correct. And I also saw a fiddle example showing that both of them work...

"You are developing an application that uses multiple asynchronous tasks to optimize performance. The application will be deployed in a distributed environment. You need to retrieve the result of an asynchronous task that retrieves data from a web service. The data will later be parsed by a separate task. Which code segment should you use?"

Option A:

protected async void StartTask()
{
   string result = await GetData();
   ...
}
public Task<string> GetData()
{
   ...
}

Option B:

protected async void StartTask()
{
   string result = await GetData();
   ...
}
public async Task<string> GetData()
{
   ...
}
Josy Sclei
  • 57
  • 1
  • 10
  • Please [edit] question to post code as text and clarify what research on the topic you already done. In particular there are plenty of questions about `async void` as well as "when to not mark method `async`". – Alexei Levenkov Aug 19 '22 at 16:08
  • Edited as requested – Josy Sclei Aug 19 '22 at 16:42
  • The "Option B" is not really an option. Take a look at this article by Stephen Cleary: [Avoid async void](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void "Async/Await - Best Practices in Asynchronous Programming"). – Theodor Zoulias Aug 19 '22 at 17:17

0 Answers0