0

What is the difference between declaring WEB API methods as the following :

  1. public async Task<IActionResult> Get() {}
    
  2. public ActionResult<IEnumerable<string>> Get()
    
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • One is asynchronous and the other is not. You can use the await keyword with number 1 but not with number 2. – Ryan Wilson May 23 '18 at 16:36
  • 1
    Why do developers use these methods ? What purpose does it serve by using method 1 and 2. Sorry I am a newbie. – Sharon Watinsan May 23 '18 at 16:40
  • With method one, you can do asynchronous programming, so, for instance, in your Controller, you want to do a file download from the database but also you need to do some other data pulls or pushes, you can use method 1 to run a task to do that process and continue with code in the main thread, spawn another task to do another file download or upload, (Parallel Programming), then await those 2 tasks to finish before returning from the method. This can be a lot faster than method 2 depending on how many actions you need to take and how many actions depend on a result from a previous action. – Ryan Wilson May 23 '18 at 16:44
  • Try reading this, it answers your question and talks about sync vs async: https://stackoverflow.com/questions/26158789/why-should-i-create-async-webapi-operations-instead-of-sync-ones – Daniel Almeida May 23 '18 at 16:44
  • @RyanWilson What about method (2) – Sharon Watinsan May 23 '18 at 16:48
  • @sharonHwk async/sync aside you should check this answer https://stackoverflow.com/a/49504573/5233410 – Nkosi May 23 '18 at 16:57
  • Is it possible to return a `bool` (a return type) with method (2) ? – Sharon Watinsan May 23 '18 at 17:02
  • @sharonHwk can you clarify that last comment about the bool? As an action can basically return any object type. It is how the framework deals with them that may differ – Nkosi May 23 '18 at 17:03
  • @RyanWilson All endpoints in an ASP application are going to run on a thread pool thread. There is no "main thread" in an ASP application. – Servy May 23 '18 at 21:50

1 Answers1

0

Method 1 is an asynchronous API Action, returning a simple ActionResult, which is a base type for action method return types.

Method 2 is a synchronous API action, returning a generic IActionResult type that encapsulates a collection of strings.

Considering the method names Get, they are the kind of APIs that you would call to get some data from a web server.

Does this answer the question?

Lucas Araujo
  • 453
  • 4
  • 14