In the earlier versions. net Framework, writing code to perform asynchronous Io operations was not possible and hence the IO operations had to be synchronous. the problems that the developers were encountering with the synchronous approach were:
1. unresponsiveness of UI-if the application is a thick client and had to perform file IO operations based on the user actions.
2. Performance issue-in case of back ground process, where it has to process large files.
In. net Framework 4.0 asynchronous Io provisions were given for classes like streamreader, streamwriter, etc. through the methods beginread, beginwrite, Etc ., involving callbacks. though it provided a way to write asynchronous code there was yet another
Drawback -- the Code complexity!
In. net Framework 4.5 the IO classes are packed with new async methods using await and async keywords, which can be used to write straight-forward and clean asynchronous Io code. below are the advantages of using these new async Io methods.
1. Responsive UI-in Windows apps, the user will be able to perform other operations while the IO operation is in progress.
2. Optimized Performance due to concurrent work.
3. Less complexity-As simple as Synchronous Code.
In this article we look at a few examples of async Io operations in. NET Framework 4.5.
Streamreader and streamwriter
Streamreader and streamwriter are the widely used file IO classes in order to process flat files (text, CSV, etc ). the 4.5 version. net Framework provides except async methods in these classes. below are some of them.
1. readtoendasync
2. readasync
3. readlineasync
4. flushasync-reader
5. writeasync
6. writelineasync
7. flushasync-writer
The code below reads the content from a given list of files asynchronously.
- namespace AsyncIOSamples
- {
- class Program
- {
- static void Main(string[] args)
- {
- List<string> fileList = new List<string>()
- {
- "DataFlatFile1.txt",
- "DataFlatFile2.txt"
- };
- foreach (var file in fileList)
- {
- ReadFileAsync(file);
- }
- Console.ReadLine();
- }
- private static async void ReadFileAsync(string file)
- {
- using (StreamReader reader = new StreamReader(file))
- {
- //Does not block the main thread
- string content = await reader.ReadToEndAsync();
- //Gets called after the async call is done.
- Console.WriteLine(content);
- }
- }
- }
- }
Now let us try with the readlineasync and read the content from a single file asynchronously.
- namespace AsyncIOSamples
- {
- class Program
- {
- static void Main(string[] args)
- {
- ReadFileLineByLineAsync("DataFlatFile1.txt");
- Console.WriteLine("Continue with some other process!");
- Console.ReadLine();
- }
- private static async void ReadFileLineByLineAsync(string file)
- {
- using (StreamReader reader = new StreamReader(file))
- {
- string line;
- while (!String.IsNullOrEmpty(line = await reader.ReadLineAsync()))
- {
- Console.WriteLine(line);
- }
- }
- }
- }
- }
In these examples the main point to note is that these asynchronous operations do not block the main thread and are able to utilize the concurrency factor.
A similar example holds good for streamwriter as well. Here is the sample code, which reads the content from a list of files and writes it to the output files without blocking the main thread execution.
- namespace AsyncIOSamples
- {
- class Program
- {
- static void Main(string[] args)
- {
- ProcessFilesAsync();
- //Main thread is not blocked during the read/write operations in the above method
- Console.WriteLine("Do something else in the main thread mean while!!!");
- Console.ReadLine();
- }
- private static async Task ProcessFilesAsync()
- {
- List<string> fileList = new List<string>()
- {
- "DataFlatFile1.txt",
- "DataFlatFile2.txt"
- };
- foreach (var fileName in fileList)
- {
- string content = await ReadFileAsync(fileName);
- WriteFileAsync(content, "Output" + fileName);
- }
- }
- private static async void WriteFileAsync(string content, string outputFileName)
- {
- using (StreamWriter writer = new StreamWriter(outputFileName))
- {
- await writer.WriteAsync(content);
- }
- }
- private static async Task<string> ReadFileAsync(string fileName)
- {
- using (StreamReader reader = new StreamReader(fileName))
- {
- return await reader.ReadToEndAsync();
- }
- }
- }
- }
WebClient
This class is used for data request operations over protocols like HTTP, FTP, etc. This class is also bundled with a bunch of async methods like downloadstringtaskasync, downloaddatataskasync and more.
It doesn't end here but extends to classes like xmlreader, textreader and more. I will leave it to the readers to need e them.
Happy reading!