Returning from an Asynchronous Method

As you’ve seen during our exploration of the asynchronous method feature, the return keyword is used to complete the returned task. Just this once, we’ll ignore the compiler warning when writing an asynchronous method that doesn’t have any await expressions inside it, to show how a simple asynchronous method is implemented under the hood.

static async Task<int> Demo(){    return 42;}

The reason the compiler complains, as shown in Figure 31.33, is that the method will complete synchronously under all circumstances. In fact, the warning suggests to introduce parallelism by using Task.Run if the method performs compute-intensive work.

FIGURE 31.33 Compiler warning when nothing is awaited.

For our purposes ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.