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

Comments

  • Just a dev

    Posted by Freddy on 01/30/2014 12:45am

    Do you have a source for your statement that in the early days of .net "writing code to perform asynchronous IO operations was not possible and hence the IO operations had to be synchronous" I'm particularly interested in the statement that .net 4 introduced async IO. Of course we've had async operations for a long time now, so I wonder if you are referring to actual async IO (IOCP and overlapped IO). If that is the case, it'd be great if you can share the source on that, as I am having trouble to find a good source on .net for support for this. ps. I guess another option that may have happened, is that you are talking about the changes in the async patterns over the years, which certainly has made it a lot better.

    Reply
  • hyXvF ryQ qoto

    Posted by HWDwcsBGdR on 07/20/2013 02:55am

    online xanax xr 1 mg twice a day - order xanax online australia

    Reply
  • Valget av hodetelefonene til drift det er en rask prosess, ettersom det er det element av livet

    Posted by mantouhmmm on 06/04/2013 05:31pm

    [url=http://www.beatsdrenorge.webgarden.com/]beats by dre norge[/url] dette er lett å finne fra ulike nettsteder som har blitt prøvd og testet over tid. De trommerytmer er en viktig og en svært viktig del av beats samling uansett hva slags valdet du skriver skal de rap beats eller Jazz slår trommer er veldig viktig siden de gir en god følelse til composition.Visit ulike nettsteder og prøve litt av beats som er der og lytte til dem og prøve hva som tilbys. Besøke nettsteder som tilhører de ulike musikkproduksjon skoler for noen tips som hjelper deg i å kombinere din gratis rap beats og andre musikksjanger beats. Å kunne laste ned beats på nettet en av hemmelighetene er å slå sammen flere e-postlister som slår nedlasting nettsteder de vil gi deg siste nytt om downloads. [url=http://www.beatsbydrestudio.moonfruit.com/]beats by dre norge[/url] Mp3-filer kan kjøpes for billige priser. De tilbyr også gratis nedlastinger for de som ønsker å teste det ut. I-Doser gir informasjon om de riktige hodetelefoner til bruk og hva slags innstilling du må være i for å få de beste effektene fra den. Den binaural beats linken nedenfor gir mer informasjon om emnet, samt gratis dataprogram og hvor du får gratis lyder mellom.Dette syv trinn formelen er prosessen med å lage beats. Beat gjør er ikke rocket science. Ved å forstå de grunnleggende prinsipper og begreper i musikkproduksjon, bør du være i stand til å gå gjennom hele prosessen med letthet og enkelhet. Akkurat som baking, musikk har sin egen formel for utvikling av en song.All musikk programmer har en lyd editor som hjelper deg i din musikk arrangement av lyder. Enten du bruker samples eller lage din egen lyd, vil du bruke en lyd editor for å skrive alle dine Beats By Dre Pro. Få en grunnleggende forståelse av hvordan musikken programvaren fungerer før du bruker denne formelen. [url=http://www.beatshodetelefoner.webstarts.com/]beats by dre studio[/url] By Dr Dre De makrokosmos kosttilskudd navn hugeness slår nær Dre Solo HD Special.Beats av Dre studio whitened sølv hodetelefoner edition rød-farget hodetelefoner for administrere diskusjon. kosttilskudd opplysninger hugeness slår nær til røde beats solo hd spesiell utgave slår nær dre solo hd gir deg lilje innenfor av dalen fineste kunnskap grunn musikk, Beats Engros hugeness nær Dr. Dre Solo HD-hodetelefoner rød-farget begrenset Edition, rundt jorden med en gang frakt og levering USD 52,30 Kina hotsale Jovial hugeness Beats By Dr Dre Solo HD for store mengder allot ingen verdi frakt og levering, kom fro her fro kjøpe Beats By Dr Dre Solo HD-hodetelefoner rød-farget, august deg 100 spesifikke monster beats bli butikk, Beats hugeness Beats By Dr.Dre Solo HD akseptable Beats By Dre Solo HD rød-farget ControlTalk begrenset Edition nær Dr. Dre Solo HD store Definition OnEar Hodetelefoner Red. elektrisk post fro bare en kompis Vær lilje innenfor av dalen nøkkelen fro evaluering dette produktet. Tilgjengelighet På lager. RegulMonster Beats-hodetelefonene Beats By Dre Solo Red.

    Reply
  • 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
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds