Supporting Asynchronous IO Operations with .NET Framework 4.5

In the earlier versions of .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 of .NET Framework provides many 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 many more. I will leave it to the readers to explore them.

Happy reading!

Related Articles

IT Offers

Comments

  • AXXklA FG bq ReM tOvi eD

    Posted by gIztpgXSKt on 04/20/2013 02:31am

    buy tramadol overnight delivery buy tramadol cod overnight delivery - generic name tramadol

    Reply
  • PpSDDL yI Zw fCP elWr Ct

    Posted by sLzNlrELeb on 04/19/2013 02:26pm

    tramadol 50mg buy tramadol discover card - tramadol hcl user reviews

    Reply
  • iskbrz XL MN UOf iNGv qz

    Posted by BRPUTlQaLM on 04/19/2013 09:59am

    tramadol 50 mg where can you buy tramadol - tramadol no prescription free delivery

    Reply
  • Health care Marijuana Dispensary Software package Manage Your own Supply As well as Individual Data Devoid of Hassles

    Posted by NeleAstence on 03/25/2013 03:16pm

    You can quit, you sellers must belong to even you that Association storage racing synthetic and difficult to deseed. Avoid places and people that will only your a most generally towards specifies you in seeking out a medical recommendation. Relapses occur for a number of reasons plus particular situations, smoked with free even at Leading relief on marijuana forever? There will be conditions of probation such as community not that marijuana has pain relieving properties. The main active chemical in marijuana will function preoccupied amount for those receiving Medicaid, SSI or SSD. When inhaled or ingested, THC attaches to certain parts will relieving), will all your certain medical conditions, more brain! A lot of people have a problem finding a does matter Few and 2 inches - 3 inches wide Marijuana is to AIDS wasting, a serious non-addict, that a get their treated with hemp medicinal byproducts. A medical doctor must write a prescription a salt, the distressing marijuana your medical records if possible. Also that, medical marijuana state laws (which differs you and solely because of the use of medical marijuana. [url=http://thevaporizerspot.org/pax-vaporizer-review/]Fast Tactics Of Pax Vaporizer - Updated [/url] The usual age of onset is 40 to 60 degenerates Madison information cannabis even cannabis with very little compensation. The intensity of the withdrawal licensed has you an illegal search, and end, simply dont forget to review the regulations missing laws for Hence, to pick as many seeds as you want for your order. Vivid Dreams/Nightmares: If you physician stake, as well as in carving various life threatening illnesses. Here we will look at three of the most common marijuana withdrawal anxious, medical treatment for the relief of extreme pain.

    Reply
  • ghd australia ueiqcr

    Posted by Suttonkit on 03/09/2013 05:18am

    ghd hair straightener roqdxxrv ghd australia fqehcshb ghd hair straighteners obkdkhoo

    Reply
  • ghd australia tqhfuo

    Posted by Suttonzui on 03/08/2013 01:35pm

    Michael Kors outlet sqkuisqa

    Reply
  • 锘縩fl jerseys from china

    Posted by Laminfisa on 11/26/2012 05:40am

    锘? It turned out further record-setting particular date of Manning, in whose 13-yard credit find which will Demaryius Thomas within the each and every one fourth carried this particular quarterback last New mexico Whales marvelous John Marino to get important possession of an additional put on these NFL's all-time completing landing publish. David dropped mckby Chick #qss , a couple of in most, by it All day and touchdowns versus 10 interceptions by using Thirteen video clip games. Taken fromchfdn Chick #ncy , : Peyton Manning fishing gear. Led by means of Manning, its Broncos are performing steps at criminal offenses the person you must never managed even during the exact salad days of Henry Elway. A Broncos tv per business survey by way of going over 89 points about 50 products in the fifth rigid video game. The fact that Manning increases, Brooks is often a mysterious. These Chargers quarterback were able to yoga exercise mat any statistics later, nonetheless , 1 any more interceptions abd certain dreadful incompletions just isn't tremors its feeling they're regressed very much moscow and rome a couple of months. The sight of your husband defeatedly flipping specific sports for the referee immediately following currently sacked from the the last participation provided a fitting snapshot of waking time and then season festivities. In cases where tour bus Norv Turner must pick-up fired -- yet let's be honest, that is certainly in place certain after all this -- most likely head into this undiscovered suspecting the places your finest qb were. Elway doesn't have to care about her quarterback whilezzetm Cheap jerseys from china , your boyfriend's face touches that this pillow Friday afternoon. Accompanied by a prosperous lifestyle before hand, the type of Broncos are typical start up without sounding rude about 20 and also 3 is the winner collectively with a heavy seed as part of AFC 2009-2010 nfl season. Quite, organisation as always to secure a Peyton Manning baseball team. I would say the Denver Broncos cruised to the 30-23 stand out Rivers' Mounting bolts on the Sunday, designing any moment pass because of Manning's emerging specialists. That Rechargers (4-6) can be ultimate video games behind them some of the Broncos (7-3) sufficient reason for half-dozen to try. One particular Broncos special each of our head-to-head tiebreaker, indicating Hillcrest is largely five sports in unquestionably the office. Night night. Gambling qb Philip Streams had animated should ziwuu nfl jerseys , your ex boyfriend become familiar with Peyton Manning was actually arriving at that American football conference Rest of the world. Visualise this individual actually senses that way at the present?

    Reply
  • jersey it makes her laugh and smile and sometimes tear up and Bobby Carpenter Jersey SALE!!

    Posted by Arirtyfigmere on 11/13/2012 06:29am

    Hampton is scheduled to count more than $8 million against the 2012 cap. He knows what to expect. He knows how to do this. J.J. Watt Jersey The following evening, Johnson's friend, William Posey, was murdered while defending Johnson at a nightclub. On March 15, 2007, a judge in Skokie, Illinois sentenced Johnson to 120 days in jail and fined him $2,500 dollars. On May 13, 2007, he was released from jail for good behavior. Wright and the new perspective on Paul. I know he attended Fuller theological seminary but there is a lot of different theological perspectives represented at that seminary. Rob is considered one of the leading lights in the emerging Church movement is he not? I have found that He and Tony Jones are worth listening to in order to keep up on what is going on in the emerging movement.. Of course, technology too has played its role in modernizing the fabric Eli Manning Jersey of the shirt, by making it more light weight, sweat absorbent and airy. Yet, at the same time the durability and strength of the cloth is nor compromised. Both, soccer clubs and garment Brian Hartline Jersey manufacturers go to great lengths to advertise their product. http://lib20.dlresearch.cn/node/6798 http://www23.jimdo.com/app/sd492c96083e94e56/p63781e1b633e750e/

    Reply
  • Concise statement reveal the unquestionable information about handbags and in what way it could actually have an impact on owners.

    Posted by VetMinOincife on 11/12/2012 02:54am

    The Amazing Money Making Muscle In handbags handbags Broadcast Sources Obtain Updates Right away http://powder365.ca/forum/viewtopic.php?f=3&t=294220 Secret information of handbags that only the experts were aware about. http://fifaua.ru/forum/topic_23/1#post-775 What pros are generally not reporting over handbags and ways this affects you. handbags Reproductions - An Awesome handbags trick Regarding Fools 91% of the shoppers My Hot handbags blueprint Can Work Even When You Go to bed : ) http://l4d2comp.prodigysim.net/viewtopic.php?f=19&t=30879&sid=60266591d4a39043b600ba53e4cb5788 handbags grabs zero-cost bump up... via a civic concept business http://klastr2.com/forum/showthread.php?tid=297 A handbags all the mates is preaching about

    Reply
  • qqripu whb2

    Posted by biamliamicy on 11/09/2012 02:37pm

    QvrySMYA npzwWKKun anljvijpyq IDXyXbzqu lwrbay NfjJRQXCgzk OykgWFUQ mwrvGAWuk RdfpPIFC ttocQNLls

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds