Navigation
Links

Powered by Squarespace
Main | IEnumerable & IObservable Split () »
Sunday
Aug282011

Different async options in .NET

To demonstrate the different async options in .NET, I wrote the following samples that call the async read methods of the .NET FileStream. The following APM, TPL, and Rx code samples complete in roughly the same amount of time. I am biased to Rx, so, it's the most elegent code sample of them all.

APM sample

int count = 0;
byte[] buffer = new byte[__bufferSize];
ManualResetEventSlim flag = new ManualResetEventSlim ();
Action read = null;
read = () => fileStream.BeginRead (buffer0__bufferSizear => {
    int bytesRead = fileStream.EndRead (ar);
    if (0 == bytesRead)
        flag.Set ();
    else {
        if (count++ > __count) {
            Console.WriteLine (stopwatch.Elapsed);
            count = 0;
        }
        read ();
    }
}, null);
 
read ();
flag.Wait ();

A counter, buffer, and waithandle are created. An action delegate calls the beginRead delegate, and registers an anonymous delegate as the callback. In this callback, the EndRead method is called which returns the bytesRead. If it's zero, the waithandle is signaled and the method exits, otherwise, a count is increased (and checked against a constant to write progress), and calls itself to loop.

TPL sample

int count = 0;
byte[] buffer = new byte[__bufferSize];
ManualResetEventSlim flag = new ManualResetEventSlim ();
 
Func<Task<int>> readAsync = () => Task.Factory.FromAsync<byte[], intintint> (
        fileStream.BeginRead,
        fileStream.EndRead,
        buffer,
        0,
        __bufferSize,
        null);
 
Action read = null;
read = () => {
    readAsync ().ContinueWith (task => {
        if (0 == task.Result)
            flag.Set ();
        else {
            if (count++ > __count) {
                Console.WriteLine (stopwatch.Elapsed);
                count = 0;
            }
            read ();
        }
    });
};
 
read ();
flag.Wait ();

An action delegate invokes the task and hooks in a continuation delegate to handle the completion. In the continuation if the result is 0 the waithandle is set and the method exists. Otherwise the count in increased  (and checked against a constant to write progress), and calls itself to loop.

Rx sample

byte[] buffer = new byte[__bufferSize];
var readAsync = Observable.FromAsyncPattern<byte[], intintint> (
    fileStream.BeginReadfileStream.EndRead);
 
Observable.Repeat (0).SelectMany (_ =>
    readAsync (buffer0__bufferSize)).TakeWhile (bytesRead =>
        bytesRead > 0).Buffer (__count).ForEach (results =>
        Console.WriteLine ("{0} min:{1} max:{2} count:{3}",
        stopwatch.Elapsed,
        results.Min (),
        results.Max (),
        results.Count));


A infinite sequence of 0 is created, the value 0 is ignored by the SelectMany operator by invoking the observable factory function, constrain the sequence to only observe when bytesRead > 0, buffer the results into a sequence of IList<int> and we block with the ForEach operator to display the progress to the console.

Thanks to David Fowler for recomending the idea to compare the differences between the different aync options in .NET!

Reader Comments (6)

I love Laura Ingalls Wilder's best-selling series of Little House, showing the warm of family with warmth style, all kinds of wonderful stories coming out one by one with brisk pace, makes me feel so pleasant.friends dvd box

November 16, 2011 | Unregistered Commenterfriends dvd box

The fake breitling watches will charge aliment because they are automated with abounding baby affective parts.There are new styles of Replica Breitling Windrider which are absolute adorable and popular. New styles of replica Breitling Navitimer can be begin at the online store.

December 15, 2011 | Unregistered Commenterardt

Austria young fellow Alabama wear cristiano ronaldo cleats is Bayern this season focuses on the cultivation object, since this summer after his nike mercurial loan to the team, the 19 year-old genius won the old heyneckes love. adidas adipure iv sl The first half of the 17 round league tournament, nike ctr360 a total of 15 Alabama debut, by virtue of a year to get a breakthrough, he wear nike total 90 was named to the annual Austria football club.

Araba Van Gaal promoted a potential new star, he wear nike ctr360 maestri ii created the Bayern and Austria national team is the most young appearance record. At the nike tiempo beginning of this year as part of the deal, Gustavo, Alabama was loaned to Hoffenheim in the first half of the year, adidas adipure and last season 's second half, he quickly won the starting position, 17 league games all the first stage. adidas predator This summer, heyncks entered Bayern on the genius of Austria wear mizuno wave cup is also quite appreciate, he refused to hire outside Alabama, and he will be the team focused on cultivating object.

In Bayern in the lionel messi soccer cleats first half of the season, Alabama 15 League appearances, the Champions League 4 appearances, he wear wayne rooney cleats has contributed 2 goals and 2 assists. cheap soccer cleats The winter before the last round of the nike tiempo legend iv home of the Bayern 3-0 victory over Cologne race in Alabama wear nike mercurial vapor superfly iii, a one-shot for the first half of the season drew satisfactory full stop.

For the average Austria's national team, Araba Hengkong wear nike total 90 laser iv born is a great gospel. And now, Alabama wear nike ctr360 maestri ii elite also harvested a honors, he was named Austria Mr. football this year, adidas f50 adizero trx this year only 19 year-old genius player record became Austria's youngest adidas adipower predator trx ever player.

December 21, 2011 | Unregistered Commenternike soccer cleats

2011/12 season, the Spanish King's Cup fourth round second leg match at the Camp Nou Stadium, fight, Barcelona 9-0 Hospitalet, Pedro wear adidas f50 adizero trx penalty advanced the ball. Andres Iniesta wear messi soccer cleats exit injured after scoring a goal, Xavier Hernandez wear adidas adipower predator sl also scored a goal. Cesc Fabregas wear nike ctr360 maestri ii elite contributed three assists. Barcelona, the other players played well, Thiago Alcantara wear nike mercurial vapor superfly iii cr, Cuenca wear nani cleats and Tello wear adidas adipure iv sl are two goals. </p>
<p>Barcelona Lineup (3-4-3): 13-Jose Manuel Pinto Colorado wear mercurial superfly iii; 3-Gerard Pique, 5-Carles Puyol wear landon donovan cleats, 24-Andreu Fontas wear wayne rooney cleats; 6-Xavier Hernandez (39', 37-Tello), 16-Sergio Busquets Burgos wear adidas adipower predator (57', 18-Giovani Dos Santos Ramirez wear nike mercurial vapor superfly iii), 11-Thiago Alcantara, 8-Andres Iniesta wear nike tiempo legend iv (31', 30-Roberto wear nike total 90 laser iv); 17-Pedro, 4-Cesc Fabregas, 39-Cuenca wear cristiano ronaldo cleats.</p>
<p>English Premier League, Manchester City 3-0 Stoke City: Manchester, Edin Dzeko wear f50 adizero trx training injury sidelined, Sergio Aguero wear nike mercurial vapor superfly iii cr7 to play striker, Mario Balotelli wear total 90 laser iv off the bench, Adam Johnson wear adidas f50 adizero trx to obtain first, Gael Clichy wear mercurial vapor iii end suspended. Stoke City defender Ryan Shawcross wear nike total 90 laser iv yellow card suspension, midfielder Glenn Whelan wear adidas adipure iv sl and fullback Andy Wilkinson wear mercurial vapor cr7 injury. Manchester City scored almost 15 minutes, Yaya Toure wear nike tiempo legend iv elite Road-point shot, Adam Johnson on the right edge of the area within the left foot shot almost cut goals. Manchester City 29 minute lead, David Silva left foot pass, Yaya Toure left the restricted area passes, Vincent Kompany wear tiempo legend iv elite at 3 m in front of the shot was Thomas Sorensen wear adidas adipower predator sl saved, Sergio Aguero wear nike mercurial vapor superfly iii goals, 1 -0. 36 minutes, David Silva wear adipower predator sl closed on the left the ball was destroyed, but the other rescue is not clean, Adam Johnson wear f50 adizero trx in front of the ball 25 meters left foot goal, 2-0. The first 54 minutes, Gareth Barry wear adipure iv sl steals front after passing, Samir Nasri wear nike ctr360 maestri ii elite restricted the right of low-pass, Sergio Aguero wear adidas adipure iv 6 meters away from the door to easily score 3-0.

December 24, 2011 | Unregistered Commentersoccer shoes

English Premier League, Chelsea 1-1 Tottenham Hotspur:English Premier League 2011/12 season, the 17th round of a match at White Hart Lane Stadium, fight, away to Chelsea 1-1 Tottenham Hotspur, Emmanuel Adebayor advanced the ball, Daniel Sturridge goal. Chelsea captain wear adidas f50 adizero micoach at 24 hours after the crime charged with racial discrimination is still first play, John Mikel and injury of Rafael Ramirez playing rotation, Frank Lampard wear cristiano ronaldo cleats into the bench. Tottenham Hotspur winger Gareth Bale wear adipure iv back from injury, Aaron Lennon wear nike ctr360 maestri ii elite injury, William Gallas and Scott Parker played.<
Tottenham Hotspur Lineup (4-4-1-1): 24-Brad Friedel wear wayne rooney cleats; 28-Kyle Walker, 13-William Gallas wear nike tiempo legend iv elite, 26-Ledley King, 32-Benoit Assou-Ekotto wear messi soccer cleats; 14-Luka Modric, 8-Scott Parker wear adidas adipower predator, 30-Sandro, 3-Gareth Bale; 11-Rafael van der Vaartwear mercurial vapor superfly iii (46', 9-Roman Pavlyuchenko); 10-Emmanuel Adebayor wear adidas adipure iv sl.
Chelsea Lineup (4-3-3): 1-Petr Cech wear nike total 90 laser iv; 17-Jose Bosingwa, 2-Branislav Ivanovic wear tiempo legend iv (33', 19-Paulo Ferreira), 26-John Terry wear adidas f50 adizero trx, 3-Ashley Cole; 12-John Mikel wear nike mercurial vapor superfly iii (48, 6-Oriol Romeu), 16-Raul Meireles wear adipower predator sl, 7-Rafael Ramirez; 23-Daniel Sturridge, 11-Didier Drogba (78', 9-Fernando Torres wear nike mercurial vapor superfly iii cr), 10-Juan Mata.

December 24, 2011 | Unregistered Commentersoccer shoes 2u

Denver Nuggets 110-85 Phoenix Suns: Denver Nuggets, Danilo Gallinari scored 23 points today, six rebounds, Kosta Koufos 15 points and 11 rebounds, Andre Miller 9 points, 10 assists and seven rebounds. Off the bench Corey Brewer wear adizero ghost 20 points. Phoenix Suns, Jared Dudley wear nike rookie lwp 17 points, is the only starting player on the double. Grant Hill wear nike hyperfuse debut, scored 5 points, Steve Nash 5 points and 8 assists. Off the bench Hakim Warrick wear adizero rose 15 points, Shannon Brown wear adizero rose 2 14 points, Markieff Morris wear nike zoom hyperfuse 12 points. Victory over the Denver Nuggets battle, Ty Lawson wear nike zoom kobe was the most eye-catching, but today he did not play, Nene Hilario wear adizero rose 2.5, Al Harrington wear nike lebron 8 ps and Rudy Fernandez wear nike lebron and others have missed. Denver Nuggets is almost the second team play, but still strive. Section 10 minutes before the two teams hard to compete, in this section have 1 minute 39 seconds, Hakim Warrick wear nike hyperdunk of two free throws, Phoenix Suns only 16-18 behind. After the more than 70 seconds as Corey brewer wear adizero crazy light the performance time, his first jump shot caused Josh Childress wear nike lebron 8 v2 foul, and even scored three points with a fine cast, and then pick Andre Miller wear nike kobe vi pass, two-thirds vote, Denver Nuggets scored eight points, 26-16 in one fell swoop to widen the gap. Section II shortly after the shooting twice, and Jared Dudley have also succeeded, Phoenix Suns launched a strong counterattack, in this section there are 3 minutes and 59 seconds, Jared Dudley wear adizero rose dominate after the third hit, they 42-36 lead. Phoenix Suns completed a 12-2 attack wave, Jared Dudley in the third wave of attacks hit twice. Carroll wear nike lebron 8 before the end of this section, two-thirds vote, Denver Nuggets to 52-50 lead again. Jared Dudley after the start of the third Section the third hit, Markieff Morris wear nike kobe vii is also twice third succeeded, Phoenix Suns to 60-56 exceeded. Unfortunately, after nearly three minutes failed to score Phoenix Suns, Denver Nuggets 14-0 wave of attacks, re-opened the gap to 70-60. Phoenix Suns lack of continuity of the attack, three after they 71-79 behind. The fourth quarter, in one fell swoop to a 17 point advantage 88-71. Until this section there are 8 minutes and 40 seconds, Phoenix Suns only the Shannon Brown wear nike lebron 9 first score. Widening gap between the two sides, after more than half of this section, Denver Nuggets to 98-77 ahead. Finally, Denver Nuggets 110-85 Phoenix Suns.

December 24, 2011 | Unregistered Commenterbasketball shoes

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>