Using async/await
C# provides the async
and await
keywords to simplify asynchronous programming:
public class Program
{
public static async Task Main()
{
StreamReader reader = new StreamReader("people");
string fileContents = await reader.ReadToEndAsync();
Console.WriteLine(fileContents);
Console.WriteLine("This line is after ReadToEndAsync");
}
}
Writing Custom Async Methods
You can wrap existing asynchronous methods in custom methods:
public static async Task<string> ReadFileAsync(string filename)
{
StreamReader reader = new StreamReader(filename);
Task<string> result = reader.ReadToEndAsync();
Console.WriteLine("This runs before the read is complete");
return await result;
}
yield return
Introduction to yield return
The yield return
statement allows you to return one element at a time in an iterator:
public static IEnumerable<int> GetNextValue()
{
int i = 1;
yield return i;
i += 1;
yield return i;
i += 1;
yield return i;
}
Lazy Evaluation with Yield Return
You can implement lazy evaluation using yield return
, which defers execution until the value is needed:
public static IEnumerable<int> LazyMap(IEnumerable<int> inputList, Func<int, int> operation)
{
foreach (var item in inputList)
{
yield return operation(item);
}
}