Async Keyword – Why Do We Need the Async Keyword?

cnet

I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler knows a method awaits something. But it seems like the compiler should be able to figure this out without a keyword. So what else does it do?

Best Answer

There are several answers here, and all of them talk about what async methods do, but none of them answer the question, which is why async is needed as a keyword that goes in the function declaration.

It's not "to direct the compiler to transform the function in a special way"; await alone could do that. Why? Because C# already has another mechanism where the presence of a special keyword in the method body causes the compiler to perform extreme (and very similar to async/await) transformations on the method body: yield.

Except that yield isn't its own keyword in C#, and understanding why will explain async as well. Unlike in most languages that support this mechanism, in C# you can't say yield value; You have to say yield return value; instead. Why? Because it was added in to the language after C# already existed, and it was quite reasonable to assume that someone, somewhere, might have used yield as the name of a variable. But because there was no pre-existing scenario in which <variable name> return was syntactically correct, yield return got added to the language to make it possible to introduce generators while maintaining 100% backwards compatibility with existing code.

And this is why async was added as a function modifier: to avoid breaking existing code that used await as a variable name. Since no async methods already existed, no old code is invalidated, and in new code, the compiler can use the presence of the async tag to know that await should be treated as a keyword and not an identifier.

Related Topic