Why do asynchronous calls in ASP.NET MVC need to be declared as such if the method they reside in is declared with the ‘async’ keyword already?

Now, there's a 99% chance that this "nitpick" I have found is entirely due to my own ignorance – I'm a junior web developer who has only been exposed to C# sporadically for a couple of months, so I apologize in advance for the probable stupidity of my question. Most of my experience is with PHP and JS.

If I have a method declared with the async keyword as such:

 public async Task<ActionResult> Create(MyObject myObject) { } 

Why do I also have to specify that LINQ statements be asynchronous explicitly like so:

 public async Task<ActionResult> Create(MyObject myObject) { if (ModelState.IsValid) { myObject.Id = Guid.NewGuid(); myObject.DisplayId = await db.MyObjects.MaxAsync(m => m.DisplayId) + 1; db.MyObjects.Add(myObject); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(myObject); } 

Can't the C# compiler be clever enough to figure out that because the method is asynychronous, the LINQ statements I want to execute within the method should be asynchronous too?

I guess my real beef with this is that there's now an asynchronous twin for most LINQ methods (SaveChangesAsync, MaxAsync, FirstOrDefaultAsync), and I have to use the await keyword every time I want to execute such calls. It seems excessively verbose and unnecessary.

If granular control over the synchronicity of the call was still needed, why didn't the C# developers simply allow for an .Await() or .Async() method that I could append?

by EchoLogic via /r/csharp

Leave a Reply