The legacy APM approach used the IAsyncResult interface to create asynchronous methods with a design pattern using two methods: BeginMethodName and EndMethodName. Let's try to understand the journey of a program from being synchronous, to an APM, and then to a task.
Here is a synchronous method that reads data from a text file:
private static void ReadFileSynchronously()
{
string path = @"Test.txt";
//Open the stream and read content.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding encoder = new UTF8Encoding(true);
fs.Read(b, 0, b.Length);
Console.WriteLine(encoder.GetString(b));
}
}
There is nothing fancy in the preceding code. First, we created a FileStream object and called the Read method, which reads the file from the disk...