Supporting asynchronous Io operations with. NET Framework 4.5

Source: Internet
Author: User

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.

 
 
  1. namespace AsyncIOSamples
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. List<string> fileList = new List<string>()
  8. {
  9. "DataFlatFile1.txt",
  10. "DataFlatFile2.txt"
  11. };
  12. foreach (var file in fileList)
  13. {
  14. ReadFileAsync(file);
  15. }
  16. Console.ReadLine();
  17. }
  18. private static async void ReadFileAsync(string file)
  19. {
  20. using (StreamReader reader = new StreamReader(file))
  21. {
  22. //Does not block the main thread
  23. string content = await reader.ReadToEndAsync();
  24. //Gets called after the async call is done.
  25. Console.WriteLine(content);
  26. }
  27. }
  28. }
  29. }

Now let us try with the readlineasync and read the content from a single file asynchronously.

 
 
  1. namespace AsyncIOSamples
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. ReadFileLineByLineAsync("DataFlatFile1.txt");
  8. Console.WriteLine("Continue with some other process!");
  9. Console.ReadLine();
  10. }
  11. private static async void ReadFileLineByLineAsync(string file)
  12. {
  13. using (StreamReader reader = new StreamReader(file))
  14. {
  15. string line;
  16. while (!String.IsNullOrEmpty(line = await reader.ReadLineAsync()))
  17. {
  18. Console.WriteLine(line);
  19. }
  20. }
  21. }
  22. }
  23. }

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.

 
 
  1. namespace AsyncIOSamples
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. ProcessFilesAsync();
  8. //Main thread is not blocked during the read/write operations in the above method
  9. Console.WriteLine("Do something else in the main thread mean while!!!");
  10. Console.ReadLine();
  11. }
  12. private static async Task ProcessFilesAsync()
  13. {
  14. List<string> fileList = new List<string>()
  15. {
  16. "DataFlatFile1.txt",
  17. "DataFlatFile2.txt"
  18. };
  19. foreach (var fileName in fileList)
  20. {
  21. string content = await ReadFileAsync(fileName);
  22. WriteFileAsync(content, "Output" + fileName);
  23. }
  24. }
  25. private static async void WriteFileAsync(string content, string outputFileName)
  26. {
  27. using (StreamWriter writer = new StreamWriter(outputFileName))
  28. {
  29. await writer.WriteAsync(content);
  30. }
  31. }
  32. private static async Task<string> ReadFileAsync(string fileName)
  33. {
  34. using (StreamReader reader = new StreamReader(fileName))
  35. {
  36. return await reader.ReadToEndAsync();
  37. }
  38. }
  39. }
  40. }
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.