@manhnguyenv

Welcome to my blog!

Asynchronous Programming

January 5, 2018 19:31

Asynchronous Programming

using System;
using System.IO;
using System.Threading.Tasks;

internal class Program
{
private static void Main()
{
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
}

private static async void CallMethod()
{
string filePath = "D:\\sampleFile.txt";
Task<int> task = ReadFile(filePath);

Console.WriteLine(" Other Work 1");
Console.WriteLine(" Other Work 2");
Console.WriteLine(" Other Work 3");

int length = await task;
Console.WriteLine(" Total length: " + length);

Console.WriteLine(" After work 1");
Console.WriteLine(" After work 2");
}

private static async Task<int> ReadFile(string file)
{
int length = 0;

Console.WriteLine(" File reading is stating");
using (StreamReader reader = new StreamReader(file))
{
// Reads all characters from the current position to the end of the stream asynchronously
// and returns them as one string.
string s = await reader.ReadToEndAsync();

length = s.Length;
}
Console.WriteLine(" File reading is completed");
return length;
}
}

Categories

Recent posts