Scott Hanselman

Teaching Kids Electronics, Computers, and Programming Fundamentals with Snap Circuits

September 13, '13 Comments [33] Posted in Daddy | Parenting | Programming
Sponsored By

I'm not particularly interested in my kids being programmers or computer people. I'd rather they be interested in life and totally geeked about something. If that's  computers, fine. If that's ballet, also fine.

That said, I think if they are going to be effective users (If not builders) I think they should have a basic sense of how electronics work.

I bought them a basic set of Snap Circuits, specifically Snap Circuits Jr. SC-100, which is just about US$20 on Amazon.

These are brilliant. Check this picture, as it's worth a thousand words and you'll get its genius immediately.

Snap Circuits SC-100

The 5 year old loves the motor and fan, as well as the speaker and noise makers. The boys have made doorbells, a light-controlled fan, lit-up LEDs and made an AM radio. Here's an Instagram Video of the 5 year old explaining his creation:

The pieces snap onto the grid with little buttons. The pieces are plastic and the wires run through them. They're not extremely resilient, in that they can break, particularly the capacitors, but it's actually nice to be able to see the resistors and other parts exposed through the plastic. It strikes a reasonable balance between being friendly to little hands, being sturdy, and actually working reliably as electronic components.

WP_20130912_18_01_15_Pro

The 5 year old is no prodigy, to be clear, but he's already getting a general sense of electrical movement. He'll say that the resistors "slow down the electricity" and that the capacitors "store it up." He knows positive and negative, and how to use a multimeter to measure voltage. (I recommend a $10 multimeter as well for debugging your projects.) He's starting to look at doorbells and remote controls differently now, which means these little projects have already achieved my goal in just a few weeks. I anticipate they'll play with them for some months, forget about them, and then rediscover Snap Circuits every few years. These toys are great for a 5 or 6 year old, but even a 12 to 14 year old could totally appreciate them. I'm even running through some of the experiments and using the millimeter to remind myself of long-forgotten concepts.

We quickly outgrew the 30 parts in the Snap Circuits Jr. Even though it has 100 projects, I recommend you get the Snap Circuits SC-300 that has 60 parts and 300 projects, or do what we did and just get the Snap Circuits Extreme SC-750 that has 80+ parts and 750 projects. I like this one because it includes a computer interface (via your microphone jack, so any old computer will work!) as well as a Solar Panel.

The Snap Circuits SC-750 is a bargain at prices like US$75 if you can find it, especially considering how many tablets, Kindles and iPads some kids have.

WP_20130910_19_23_04_Pro

The next Snap Circuits kids we're considering are either Snap Circuits "Light" that includes LEDs and Fiber Optics, although the 5 year old is pressuring me for the Snap Circuits Robot Rover. It'll likely be the Rover for the holidays around here.

I have no relationship with Snap Circuits, I bought these kits on my own and am reviewing them because they are awesome. If I could invest in Elenco Electronics, I would. The links here are Amazon affiliate links. If you use them, I can buy more Snap Circuits! ;)


Sponsor: Big thanks to Infragistics for sponsoring the feed this week! Download Your Free HTML5/jQuery Grid:  Prepare to launch eye-popping, performance-driven HTML5 applications with Ignite UI. Believe your eyes - you can download the world's fastest, most reliable jQuery Grid now - no strings attached!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Our first year. A new web conference - <anglebrackets>

March 8, '13 Comments [22] Posted in HTML5 | Programming | Speaking | Web Services
Sponsored By

anglebrackets conferenceThere's a new web conference happening in Vegas next month and you should join us. John Papa, myself and our friends pulled in the speakers from a combination of invitations and submitted talks. It's called anglebrackets.org and I hope to see you there.

My friends and I miss the old Mix conference and the great fun of web conferences in Vegas generally. So we talked to Richard Campbell and some friends and made our own show. (This is not a Microsoft show, to be clear)

This is the first year of anglebrackets and it's going to be a small conference and we have no money. Because of this, we are co-located with a larger conference* and attendees can move between the two conferences.

You'll be able to enjoy web-focused, back-end non-specific web sessions from amazing web people like:

  • Lea Verou - Developer Relations at the @W3C
  • Christian Heilmann - Mozilla
  • Jonathan Snook - SMACSS.com Author
  • Elijah Manor - jQuery expert
  • Jim Cowart - appendTo()
  • Denise Jacobs - Creativity Evangelist
  • Phil Haack - GitHub
  • Scott Hanselman (me) - Web guy
  • and more!

We've got killer sessions like:

  • The Vanilla Web Diet
  • Modern JavaScript Development
  • Hands On Responsive Design with Twitter Bootstrap
  • Rich Data HTML Apps with Breeze
  • Getting Started with Require.js
  • TML5 Canvas and Kinetic.js
  • Eventing and Messaging in JavaScript
  • plus talks on SignalR, ASP.NET, PHP, Backbone, CSS, JavaScript Patterns, Gamifying your work, and lots more.

AUqYiSFK3v_1_1303867939All this and a special keynote from Mozilla Web Guy Christian Heilmann!

This conference will be a great way for you to get up to date on the modern web but also check out some of the DevIntersection talks on ASP.NET, Architecture, Elastic Scale in the cloud and more.

We're lean and mean and independent and we hope you join our first year.

If you register for the show package or complete package you'll also get your choice of a Google Nexus 7 or a Microsoft Surface RT.

There's also some excellent pre- and post-conference workshops you should consider enrolling in:

  • April 8th
    • Day of Single Page Applications - John Papa, SPA and JavaScript expert
    • On the Metal: Essential HTML5, CSS3 and JavaScript for All Developers (Bring your laptop!) - Todd Anglin, Telerik
    • Hacking the Creative Brain: Work Better, Produce More - Denise Jacobs, a TEDx speaker, Creativity Evangelist, and author of CSS Detective
    • Nimble and fast web apps for the mobile web - Christian Heilmann, Mozilla
  • April 12th
    • Building Applications with ASP.NET MVC 4 - K. Scott Allen, Author, Trainer and Consultant
    • User Experience Design for Non-Designers: An Interactive, Immersive Workshop - Billy Hollis, UX and App expert

The Complete Package includes TWO workshops plus the tablet, and the Show Package includes one workshop and the tablet, or just come to the main conference itself.

See you there!

* Yes, we took a little artistic license with the <tag/>, or <tag />, or <tag> if you are super pedantic. It is valid syntax although HTML5's opinion is different than XHTML's. The fact that you even noticed and want to argue is proof you should come to this conference. See what I did there?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Programming's not for you? How about thinking? Be empowered.

March 4, '13 Comments [37] Posted in Musings | Programming
Sponsored By

Used under CC via http://www.flickr.com/photos/dellphotos/6151875304/There seems to be two extremes of this whole "Learn to Code" movement which has come to a crescendo with the "What most schools don't teach" video from Code.org.

People seem to fall on the side of "Everyone should learn to code! Teach the babies Common Lisp!" or "Not everyone can be a programmer! Relax!"

Surely we can ALL agree that this discussion isn't about code at all. "Code" is just a convenient and press-friendly way to say "think in algorithms, think about problems, think about how things fit together."

It seems a little disingenuous to focus so much on teaching first graders to code or third graders about robots while simultaneously shuttering music, art and drama programs. Our expectations of our students when it comes to math, with some suggesting we stop teaching algebra.

We need to teach kids to think and to be excited about thinking.

Code should be taught - in age appropriate ways - as part of a larger "solving problems" curriculum.

Thinking should be cool.

Why is everyone trying to get everyone else to code? One word: Empowerment. Code represents power. The power to create, the power to change, the power to influence. Code also represents money to many. It is a raw representation of both intellect and instinctually property.

But woodworking, art, sculpture, drama and music are all ways to create and influence. They just don't have price tags as impressive.

There's clearly a Digital Divide and it's bigger than just blue collar and white collar workers. It's as big as the STEM (science technology engineering math) divide. Are you a computer person? Or not?

A family friend almost lost their domain a few months back. Had they lost it, it would have decimated their whole non-technical business. It was extremely confusing for them to tease out the difference between who owned the domain and held it, who hosted the DNS and who hosted the site. In their case, GoDaddy controlled it ALL and they got locked out of everything. An hour of whiteboarding and some moving things around got them setup at DNSimple and SquareSpace and put them in control of the tech they cared about.

I hate to see small businesses being charged thousands for things they could easily do themselves.
- Said the Software Engineer who hired a guy to fix his toilet.

How/when could they have learned this incantation? In school? on TV? Or should they have puzzled it out themselves? How far should it go?

Learn the Basics. If you're excited, learn more.

Learning to code, to me, is no different from me having someone teach me basic woodworking, gardening, or kitchen tile. After each of these projects my sense of personal empowerment increased. In each situation learned how to think about a problem and solve it. I can do this. I can change my world.

Take a minute and read 101 Basic Homesteading Skills. I came out knowing about 9 of these, thereby ensuring my quick death in the coming Zombie Apocalypse.  There's a great video of Mike Rowe about how many 'dirty jobs' are available but folks either lack the skills or interest to do them.

We should learn a little of everything and a lot about the essentials. Is learning to code essential? No, not yet. but learning to think about abstractions is.

Maybe you won't be able to create swim lane overlay graphics entirely in CSS3 but you should hopefully get the gist and be excited about how freaking cool it is.

Reading, Writing, Arithmetic, and Algorithms

But perhaps it is time for "Reading, Writing, Arithmetic, and Algorithms" in school. For loops, while loops. I love this idea on "How to train your robot. The parents are the robots and the kids give them a list of instructions (a "program") to accomplish a simple task. A kinesthetic and tactile way to teach a young kid to think without staring at a screen. Read more about this at OffBeatFamilies and get the materials at Dr. Techniko's blog.

Image borried from OFFBEATFAMILIES. Read their article and love them!

Procedural and Functional thinking, as well as other concepts like Project Management and Time Management are essential components of an empowered individual. These are teaching people to think. Teach them a little code and a little music and a little art, then nurture their excitement and try to turn it into empowerment. Everyone should get a chance and be exposed to all of this.

At the very least, I'd love for everyone to come out of high school with enough math/science/technology be able to wallow in the magic and wonder of the greatest joke ever (origin unknown). ;)

An engineer walks into a bar and orders 1.0E20 root beers.
Bartender: "That's a root beer float."
Engineer: "Make it a double."

I'm still giggling at this one, years later.

What do you think?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

New Interview Questions for Senior Software Engineers

February 17, '11 Comments [158] Posted in Learning .NET | Programming
Sponsored By

I'm putting together some practice interview questions for a friend who lost his job. I thought it'd be useful to crowd-source some questions from you, Dear Reader.

These questions should be more software design focused, less technical trivia like my previous two lists of interview questions:

UPDATE: I think we all agree (or at least we should) that if you go into an interview tomorrow and you look across the table and the interviewer has simply printed out this list and is reading from it, that you should excuse yourself and run. This isn't a "guide to how to interview" nor is this meant to me a "best practices for engineers" list. It's simply a collective brain-dump of stuff that someone who's been in the business of developing software for money for 10 or so years should have some passing familiarity with. Of course, it's assumed that the interviewer is able to detect BS. This isn't, and shouldn't be, a trivia contest. If you're going to get a job (or you're looking for hire someone for a job) it's ultimately more important to understand if someone can Solve Problems and if Their Head is Screwed on Straight. Take it with a grain of salt, friends, remember, you found it on the Internet. - @shanselman

Here's what I have so far.

  • What is something substantive that you've done to improve as a developer in your career?
  • Would you call yourself a craftsman (craftsperson) and what does that word mean to you?
  • Implement a <basic data structure> using <some language> on <paper|whiteboard|notepad>.
  • What is SOLID?
  • Why is the Single Responsibility Principle important?
  • What is Inversion of Control? How does that relate to dependency injection?
  • How does a 3 tier application differ from a 2 tier one?
  • Why are interfaces important?
  • What is the Repository pattern? The Factory Pattern? Why are patterns important?
  • What are some examples of anti-patterns?
  • Who are the Gang of Four? Why should you care?
  • How do the MVP, MVC, and MVVM patterns relate? When are they appropriate?
  • Explain the concept of Separation of Concerns and it's pros and cons.
  • Name three primary attributes of object-oriented design. Describe what they mean and why they're important.
  • Describe a pattern that is NOT the Factory Pattern? How is it used and when?
  • You have just been put in charge of a legacy code project with maintainability problems. What kind of things would you look to improve to get the project on a stable footing?
  • Show me a portfolio of all the applications you worked on, and tell me how you contributed to design them.
  • What are some alternate ways to store data other than a relational database? Why would you do that, and what are the trade-offs?
  • Explain the concept of convention over configuration, and talk about an example of convention over configuration you have seen in the wild.
  • Explain the differences between stateless and stateful systems, and impacts of state on parallelism.
  • Discuss the differences between Mocks and Stubs/Fakes and where you might use them (answers aren't that important here, just the discussion that would ensue).
  • Discuss the concept of YAGNI and explain something you did recently that adhered to this practice.
  • Explain what is meant by a sandbox, why you would use one, and identify examples of sandboxes in the wild.
  • Concurrency
    • What's the difference between Locking and Lockless (Optimistic and Pessimistic) concurrency models?
    • What kinds of problems can you hit with locking model? And a lockless model?
    • What trade offs do you have for resource contention?
    • How might a task-based model differ from a threaded model?
    • What's the difference between asynchrony and concurrency?
  • Are you still writing code? Do you love it?
  • You've just been assigned to a project in a new technology how would you get started?
  • How does the addition of Service Orientation change systems? When is it appropriate to use?
  • What do you do to stay abreast of the latest technologies and tools?
  • What is the difference between "set" logic, and "procedural" logic. When would you use each one and why?
  • What Source Control systems have you worked with?
  • What is Continuous Integration?  Have you used it and why is it important?
  • Describe a software development life cycle that you've managed.
  • How do you react to people criticizing your code/documents?
  • Whose blogs or podcasts do you follow? Do you blog or podcast?
  • Tell me about some of your hobby projects that you've written in your off time.
  • What is the last programming book you read?
  • Describe, in as much detail as you think is relevant, as deeply as you can, what happens when I type "cnn.com" into a browser and press "Go".
  • Describe the structure and contents of a design document, or a set of design documents, for a multi-tiered web application.
  • What's so great about <cool web technology of the day>?
  • How can you stop your DBA from making off with a list of your users’ passwords?
  • What do you do when you get stuck with a problem you can't solve?
  • If your database was under a lot of strain, what are the first few things you might consider to speed it up?
  • What is SQL injection?
  • What's the difference between unit test and integration test?
  • Tell me about 3 times you failed.
  • What is Refactoring ? Have you used it and it is important? Name three common refactorings.
  • You have two computers, and you want to get data from one to the other. How could you do it?
  • Left to your own devices, what would you create?
  • Given Time, Cost, Client satisfaction and Best Practices, how will you prioritize them for a project you are working on? Explain why.
  • What's the difference between a web server, web farm and web garden? How would your web application need to change for each?
  • What value do daily builds, automated testing, and peer reviews add to a project? What disadvantages are there?
  • What elements of OO design are most prone to abuse? How would you mitigate that?
  • When do you know your code is ready for production?
  • What's YAGNI? Is this list of questions an example?
  • Describe to me some bad code you've read or inherited lately.

Your thoughts? I'll add good questions from the comments throughout the day.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Back to (Parallel) Basics: Don't Block Your Threads, Make Async I/O Work For You

November 15, '10 Comments [11] Posted in Back to Basics | Learning .NET | Programming | Source Code
Sponsored By

Stephen Toub is one of my favorite folks at Microsoft. I've asked him questions before, sometimes for myself, sometimes on your behalf, Dear Reader, and I've always received thoughtful and well reasoned answered. Because I believe strongly in Jon Udell's "Conserve Your Keystrokes" philosophy, I always try to get great information out to the community, especially when it's been emailed. Remember, when you slap the keyboard and write an epic email to just a few people, there's millions of people out there that miss out. Email less, blog more. More on this in a moment.

TIP: If you're interested in Patterns for Parallel Programming, run, don't walk, and download the FREE and extensive eBook called, yes, you guessed it, Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4. Yes, that title is long, but it feels shorter if you process it in parallel. Seriously, it's free and there's a C# and Visual Basic version. It's brilliant.
Now, if you're REALLY interested in the topic, go get the book Parallel Programming with Microsoft .NET by Stephen Toub, Ade Miller, Colin Campbell, and Ralph Johnson. The complete book as HTML is also hosted here.

I recently noticed a blog post from my friend Steve Smith where he shares some quick sample code to "Verify a List of URLs in C# Asynchronously." As I know Steve wouldn't mind me digging into this, I did. I started by asking Stephen Toub in the Parallel Computing group at Microsoft.

Steve Smith wanted to verify a list of URLs for existence. This is the basic synchronous code:

private static bool RemoteFileExists(string url)
{
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
var response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}

Then Steve changed the code to be Parallel using the new Parallel features of .NET 4 as Stephen Toub helped me explain in "Back to Parallel Basics" in April.

var linkList = GetLinks();

Action<int> updateLink = i =>
{
UpdateLinkStatus(linkList[i]); //fetch URL and update its status in a shared list
};
Parallel.For(0, linkList.Count, updateLink);

Using Parallel.For is a really great way to introduce some basic naive parallelism into your applications.

I'm no expert in parallelism (I've read a great whitepaper...) but I asked Stephen Toub if this was the best and recommended way to solve this problem. Stephen responded from a plane using (his words) "email compiled and tested" examples. With his permission, I've included a derivation of his response here in this blog post for my own, and possibly your, edification.

From Stephen:

First, it looked like the author was proposing using a parallel loop to handle this.  That's ok, and certainly easy, but that’s the kind of thing you’d only really want to do in a client application and not a server application.  The issue here is that, while easy, it blocks threads; for a client application, having a few more threads that are blocked typically isn’t a big deal; for a server app, though, if for example you were doing this in response to an incoming ASP.NET or WCF service request, you'd be blocking several threads per request, which will greatly hinder scalability.  Still, to get up and running quickly, and if the extra few threads isn’t problematic, this is a fine way to go. 

Assuming you want you "fan out" quickly and easily and it's OK to block a few threads, you can either use a parallel loop, tasks directly, or Stephen's personal favorite, a PLINQ query, e.g. if I have a function "bool ValidateUrl(string url);", I can use PLINQ to process up to N at a time:

bool [] results = (from url in urls.AsParallel() select ValidateUrl(url)).ToArray();

In this example, PLINQ will use up to N threads from the ThreadPool, where N defaults to Environment.ProcessorCount, but you can tack on .WithDegreeOfParallelism(N) after the AsParallel() and provide your own N value.

If Steve was doing this in a console app, which is likely, then as Stephen points out, that's no big deal. You've usually got threads to spare on the client. On the server side, however, you want to avoid blocking threads as much as you can.

A better solution from a scalability perspective, says Stephen, is to take advantage of asynchronous I/O.  When you're calling out across the network, there's no reason (other than convenience) to blocks threads while waiting for the response to come back. Unfortunately, in the past it's been difficult to do this kind of aggregation of async operations.  We' need to rewrite our ValidateUrl method to be something more like:

public void ValidateUrlAsync(string url, Action<string,bool> callback);

where the method returns immediately and later calls back through the provided callback to alert whether a given URL is valid or not.  We'd then change our usage of this to be more like this. Notice the use of using System.Collections.Concurrent.ConcurrentQueue representing a thread-safe first in-first out (FIFO) collection, and CountdownEvent, that represents a synchronization primitive that is signaled when its count reaches zero.

using(var ce = new CountdownEvent(urls.Length))

{
var results = new ConcurrentQueue<Tuple<string,bool>>();

Action callback = (url,valid) =>
{
results.Enqueue(Tuple.Create(url,valid));
ce.Signal();
};

foreach(var url in urls) ValidateUrlAsync(url, callback);

ce.Wait();
}

Assuming ValidateUrlAsync is written to use async, e.g. (you'd really want the following to do better error-handling, but again, this is email-compiled):

public void ValidateUrlAsync(string url, Action<string,bool> callback)
{
var request = (HttpWebRequest)WebRequest.Create(url);
try
{
request.BeginGetResponse(iar =>
{
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(iar);
callback(url, response.StatusCode == HttpStatusCode.OK);
}
catch { callback(url, false); }
finally { if (response != null) response.Close(); }
}, null);
}
catch { callback(url, false); }
}

This example would then this would end up only blocking the main thread launching all of the requests and then blocking waiting for all of the responses, rather than blocking one thread per request.  With a slight change, we could also make the launcher async, for example:

public static void ValidateUrlsAsync(string [] urls, Action<IEnumerable<Tuple<string,bool>> callback)
{
var ce = new CountdownEvent(urls.Length);
var results = new ConcurrentQueue<Tuple<string,bool>>();
Action callback = (url,valid) =>
{
results.Enqueue(Tuple.Create(url,valid));
if (ce.Signal()) callback(results);
};
foreach(var url in urls) ValidateUrlAsync(url, callback);
}

Still, this is all really complicated, and much more difficult than the original one-liner using PLINQ. 

This is where Tasks and the new Async CTP come in really handy. Imagine that instead of

void ValidateUrlAsync(string url, Action<bool> callback);

we instead had

Task<bool> ValidateUrlAsync(string url);

The Task<bool> being returned is much more composable, and represents the result (both the successful completion case and the exceptional case) of the async operation. 

BETA NOTE: It's not possible to have both ASP.NET MVC 3 and the Async CTP installed at the same time. This is a beta conflict thing, it'll be fixed, I'm sure.

If we had such an operation, and if we had a Task.WhenAll method that took any number of tasks and returned a task to represent them all, then we can easily await all of the results, e.g.

bool [] results = await Task.WhenAll(from url in urls select ValidateUrlAsync(url));

Nice and simple, entirely asynchronous, no blocked threads, etc. 

(Note that in the Async CTP, Task.WhenAll is currently TaskEx.WhenAll, because since it was an out-of-band CTP we couldn't add the static WhenAll method onto Task like we wanted to.)

With the Async CTP and the await keyword, it's also much easier to implement the ValidateUrlAsync method, and to do so with complete support for exception handling (which I didn't do in my previous example, i.e. if something fails, it doesn't communicate why).

public async Task<bool> ValidateUrlAsync(string url)
{
using(var response = (HttpWebResponse)await WebRequest.Create(url).GetResponseAsync())
return response.StatusCode == HttpStatusCode.Ok;
}

Even without the Async CTP, though, it's still possible to implement ValidateUrlAsync with this signature.

Notice the use of System.Threading.Tasks.TaskCompletionSource. From MSDN:

In many scenarios, it is useful to enable a Task (Of(TResult)) to represent an external asynchronous operation. TaskCompletionSource (Of( TResult)) is provided for this purpose. It enables the creation of a task that can be handed out to consumers, and those consumers can use the members of the task as they would any other.

public Task<bool> ValidateUrlAsync(string url)
{
var tcs = new TaskCompletionSource<bool>();
var request = (HttpWebRequest)WebRequest.Create(url);
try
{
request.BeginGetResponse(iar =>
{
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.EndGetResponse(iar);
tcs.SetResult(response.StatusCode == HttpStatusCode.OK);
}
catch(Exception exc) { tcs.SetException(exc); }
finally { if (response != null) response.Close(); }
}, null);
}
catch(Exception exc) { tcs.SetException(exc); }
return tsc.Task;

}

So, with this method, even without the Async CTP, we can use existing .NET 4 support to handle this relatively easily:

Task.Factory.ContinueWhenAll(
(from url in urls select ValidateUrlAsync(url)).ToArray(),
completedTasks => { /* do some end task */ });

Now, using just what comes with .NET 4 proper I get the best of all worlds.

Big thanks to Stephen Toub. There's lots of new high- and low-level constructs for Task creation, Threading, and Parallelism in .NET 4. While the naive solution is often the right one, the components we have to work with in .NET 4 (and the even newer ones in the Visual Studio 2010 Async CTP adding the 'await' and 'async' keywords) will give you surprisingly fine-grained control over your multi-threaded parallel systems without a whole lot of code.

Related Links:

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Page 1 of 54 in the Programming category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.