GameFly Is Actually Pretty Great

The way I play games has changed pretty drastically recently, as I’ve subscribed to GameFly. I really can’t suggest it enough to hardcore console gamers (sadly, but as is expected these days, there’s no support for PC games on GameFly). There are a few reasons for my enthusiasm:

  • Its cheaper. If you’re like me, you want to buy 1-2 games during the slow months of the year and 2-4 games during the busier months. That ends up as a big hunk of change, especially if buying the latest releases. GameFly ends up costing around $240/year for me, which equals out to the cost of four games per year. I usually end up buying some of the games I really enjoy anyway, but I can play them when they come out (or close to) and buy them when they’ve gotten a little more affordable. Even with those and the PC games I buy, I still spend less than I would otherwise.
  • I can play games I wouldn’t have otherwise. I haven’t rented a game since middle school; I just don’t have the time to get through a game in the week they allot for you. Buying games is expensive, so I would never buy a game I didn’t fully expect to enjoy. With a flat monthly fee and any game I want to play, I end up trying things out a lot more and expand my horizons. I never would have played Call of Juarez: Bound in Blood without GameFly, but I can honestly say that the game enriched my perspective as a gamer.
  • I don’t have to buy a game I would only play once. Another negative to buying games is you might only play it once, then all you can do is sell it back at a terrible rate, put it out on craigslist, or let it collect dust on your shelf. There’s no way I would play Prototype again, but it was fun enough to complete and send back.
  • I can keep it if I like it. If I end up really liking a game and not wanting to wait for it to get cheaper, I can just keep what I have.  This was really nice when I kept Call of Duty: Modern Warfare 2 because it was a brand new copy and I got it for $10 off the retail price.
  • It helps manage my backlog. I typically have a list of games I want to play at any given time.  Having a queue of games helps me to keep track of the games I want to get to, as well as eventually get them to me.

It also changed the way I play games. Before, I would play a game to completion, no matter what I thought of it. Now that I have a list of 30 games that I’m interested in playing, I might stop playing a game before I finish it in order to get the next one. It might be that I didn’t like it (e.g. Scribblenauts, which wasn’t fun beyond its “summon anything” gimmick), or it just stopped being fun (e.g. X-Men Origins: Wolverine was actually really fun, but got quite repetitive).

Thinking of getting GameFly?  You can sign up here and get me some referral cash for me to spend on the next game I keep (yes, they have a refer-a-friend program as well).

Attaching to WndProc in WPF

WPF, like any other UI program, has an inner loop that continually runs in order to update the state of the application and render the UI.  One part of this loop is a call to the function WndProc, which is the function through which Windows communicates the messages your window is receiving (be it input or system notifications).

WPF hides this function from you (presumably to make things easier) and instead just fires events off for anything [it thinks] you’ll ever need.  Sometimes, however, it is useful to attach to this loop in order to address messages that don’t have a related WPF event, such as messages sent by other applications.

Here’s how you do it.

In your window’s SourceInitialized event, create an HwndSource object from your window’s handle. Use the AddHook method to attach an event handler to all of your window’s events using the supplied function.

private void Window_SourceInitialized(object sender, EventArgs e)
    IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
    HwndSource src = HwndSource.FromHwnd(windowHandle);
    src.AddHook(new HwndSourceHook(WndProc));

As its always good practice to define the methods you reference, be sure to define WndProc and, hopefully, do something useful with it. Its parameters describe the message by giving you its ID, as well as the parameters sent along with it. For some more on windows messages, check out my earlier post regarding emulating those messages. If your desired message has been captured and handled, be sure to set handled to true.

private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    // address the messages you are receiving using msg, wParam, lParam
    if (msg == WM_LOOK_FOR_DROIDS)
        if (wParam == DROIDS_IM_LOOKING_FOR)
            handled = true;
    return IntPtr.Zero;

Lastly, be sure to remove the hook when your window is closing.

private void Window_Closing(object sender, EventArgs e)
    IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
    HwndSource src = HwndSource.FromHwnd(windowHandle);
    src.RemoveHook(new HwndSourceHook(this.WndProc));

Easy as pie. If you’re feeling nostalgic and don’t want to use events, you can implement your entire application in the WndProc method (other than the rendering, which WPF also hides from you). I wouldn’t recommend it, though…

Video Game Review: Assassin’s Creed II (360)

It’s been awhile since I’ve done a review, and, to commemorate the occasion, I’m going to change the format again!  I found the positives vs. negatives approach rather stifling, but didn’t want to stick myself to a particular template.  So, I’m just going to write about whatever I feel deserves mentioning.

Yes, that’s correct.  My new format is no format.  Free the birds, whisper to the trees, and run naked down the beach.  Down with the restrictions of video game review formats.

Once you’ve gotten your clothes back on, come on back and read my review for Assassin’s Creed II.

In this sequel to one of my favorite games of 2007, Desmond explores the life of another of his assassin ancestors – an Italian named Ezio who lived during the Renaissance.  My first impressions of the assassins of this game were that they seemed far less epic than they did in the previous game. Altaïr’s assassins appeared to be in training for the majority of their lives, whereas Ezio becomes an assassin as a young adult and immediately becomes accustomed to the skills an assassin requires. There are other assassins, from Ezio’s pudgy old uncle to the angsty, pissy historian, who detracted from the mystery and skill apparent in the Altaïr’s brethren.

Desmond’s story isn’t very prevalent in Assassin’s Creed 2, much to my dismay.   The back-and-forth of revelations was an interesting narrative approach in the first game, and there is far less of it here. I like where it is headed, though; they are exploring the effects of the Animus, as well as pushing Desmond toward becoming a member of the modern-day assassins.

Ezio’s story, luckily, is fully fleshed out and just as interesting.  Ezio is a much more developed character than Altaïr, making it easy to relate to him; though, admittedly, it leaves much less mystery around him.  The interaction between Ezio and the supporting cast is excellent, with Leonardo da Vinci as my favorite NPC to visit.

The missions are greatly varied and each has a unique purpose, unlike the repetitious tasks of the previous entry. An unfortunate side effect of this is that the concept of performing in-depth research on a target before striking is mostly lost, making Ezio’s skills seem far from Altaïr’s methodical approach.

As I started to relearn the controls, I remembered that the puppetry metaphor they use (assigning face buttons to specific parts of the body) can make things a little confusing.  The button for interacting with an object depends on the interaction itself, unlike the dedicated interaction button used in most games. Movement is also complicated; you must hold down three buttons simultaneously to run and climb, which is what you are doing about 80% of the time. All of the face buttons are context-sensitive, making it hard to pick up at first. How many other games have you seen that have the controls as part of the HUD?

After I was reacclimated to the controls, the game started to feel familiar. Remaining hidden and eluding enemies is much easier with the ability to hide in any group and hire people to distract the guards.  Assassinations are easier to execute without being discovered, but you are still always forced to run after the fact.  The combat is still very counter-based, forcing you to be more strategic and precise.  It is greatly improved by the ability to strip an enemy of his weapon and use it against him; however, if you didn’t enjoy the combat from the last game, there will be little here to change your opinion.

Exploration is a blast, as you can explore the culture and architecture of the Renaissance.  You can research painters and landmarks from the time, which satisfies the history nut in me.  There are also story-related unlockables strewn about the city, motivating you to explore the world more completely.

One of the story-related unlockables is a series of puzzles revealing a video that unravels more about the origin of the Pieces of Eden.  The challenge of solving the puzzles ranges from mentally stimulating to mind-numbingly difficult, as some make little sense.  They often have you translating symbols to numbers, but the symbols often don’t translate in a logical way.  As an example, one in particular (spoiler for the rest of the paragraph) had the symbols depicting a base 3 number system using dots and lines (∙,∙∙, |, |∙, |∙∙, etc.).  This much I got on my own; though I doubt someone who hadn’t studied number systems would pick up on it very easily.  What I didn’t get was why the number system started at an arbitrary point – that is, instead of starting with a single dot (∙), the series starts in the middle and wraps around.  That makes the series, from 0-9, (||, ||∙, ||∙∙, |||, |||∙, ∙, ∙∙, |, |∙, |∙∙).  There are clues in a series of several pictures – that is to say, in one picture, there’s a two, and in another, the symbol “||∙∙”.  But these pictures are small and hard to see, with the symbols cryptically hidden within.

Lastly, I have to mention that the game comes with some serious technical problems.  Ezio would occasionally lose his ability to grip some objects or would become permanently affixed to something he was climbing.  The direction at which he would jump would not always feel consistent with the direction I was pushing towards, causing Ezio to fall to his death.  Strange graphical glitches would occur as well, contorting Ezio’s body in strange directions.  It was playable most of the time, but there were areas that were consistently problematic that I had to avoid.

Assassin’s Creed II left me very satisfied, but ready for more.  The fact that we’ve explored two unique landscapes within the same story has been amazing, making me disappointed to hear that Assassin’s Creed III will continue exploring the Renaissance period with Ezio.  I remain excited about the series, however, and can’t wait to see it conclude.

Have you played Assassin’s Creed II?  What are your thoughts?

The New HP TouchSmart PCs

For the past year and a half, I’ve been working on software for HP’s TouchSmart all-in-one PCs. I develop and manage the deliverables for some of the tiles found within the TouchSmart software suite.  Allow me to take a moment and give you a TouchSmart commercial, explain my role in its creation, and how you can develop on the platform.

Two New TouchSmarts

HP released (in October – yes, this post is a tad late) two new TouchSmarts to coincide with the release of Windows 7, the 300 and 600 series. The 600 is the more performant and larger of the two, but both retain the same touch technology and form factor.  It sports the Core 2 Duo, while the smaller brother uses a 64-bit AMD processor.  You can pick and choose various components for the 300 and 600 at HP’s shopping site, so be sure to check out the specs there if you’re interested in more details.

The TouchSmarts use optical touch solutions, using two infrared sensors to triangulate the positions of up to two touches. This 2-camera system presents some inaccuracies when two touches are involved, and it certainly created some challenges for my own development. These restrictions are found in all of the multi-touch all-in-ones currently in the market, as they are all based on the same technology, but our mathemagicians perform some voodoo on the data to more accurately approximate the location of the user’s fingers. It is a much more cost-effective solution when compared to capacitive touch screens, such as the iPhone’s, as the cost for that type of screen exponentially increases with surface area.

The TouchSmart software suite has seen quite a few changes itself. In case you are not familiar with the TouchSmart software for the 500 and 800 series (TouchSmart 2.0), it is a collection of touch-based applications displayed in two scrollable rows of “tiles”. These tiles are not interactive in this view, but the user can view information in each tile. To interact with the tile, the user taps on it and enters the full view of the application. You can find a video showing the framework here.

TouchSmart 2.0

TouchSmart 2.0

The big change in TouchSmart 3.0 is interactive tiles. The top row’s tiles have been widened and the user can now interact within each tile. Not only that, but the list of TouchSmart applications has grown beyond 20, and each of the existing applications have seen major enhancements.  A video for the new framework can be viewed here.

TouchSmart 3.0

My Role

The four applications for which I am responsible are:

Create collages and tag your photos using multitouch gestures or voice commands. I was the developer on this application, which sprung from a sample application that I wrote to show our vendors how to calculate the touch gestures. You may have seen some of the results of that sample early if you’ve been traveling through Chicago recently, as the application being demoed is using a library I wrote.  Here, you can find a tutorial video (without voice commands but surely some bugs, since the video was shot far before we shipped).

Watch videos on Hulu through the touch-friendly interface of Hulu Desktop, residing in the TouchSmart framework. This application was developed by Hulu, but I manage the deliverables for it, provide technical consultation for its integration, as well as ensure it passes through our qualification process.

Twitter client for TouchSmart. If you’re into Twitter, you’ll know what’s here (it’s the standard fare for Twitter apps). If you’re not, you don’t care anyway. My responsibilities for this app are similar to my responsibilities for Hulu.

Clock application for TouchSmart. It’s identical to the TouchSmart 2.0 version, but has been updated to work with 3.0 and ported to Windows 7.

As I mentioned above, there are over 20 applications for the TouchSmart, so what I’ve done barely scratches the surface. The two teams working on the suite worked incredibly hard and have pulled off some amazing stuff. There are apps from photo editing to recipe management. For a full description of all of the applications, you can find them here.

How You Can Get Involved

You are free to create your own TouchSmart tiles if you have an idea for a touch application that would fit well within the TouchSmart framework. It is rather simple – in fact, an existing windows application can be living nicely in TouchSmart within a couple hours of development.

You can find the TouchSmart 3.0 SDK at the TouchSmart Dev Zone, a community based around TouchSmart application development.  Be sure to get involved here, as there are plenty of people willing to aid you in your development, and you can submit your completed application to this site for distribution.

The biggest highlight to this new SDK is that there is now a library for WPF to help you through some of the requirements for TouchSmart applications.  In it, you’ll find a Window class that will define your window with the necessary properties for a tile (no chrome, layout notifications, off-screen launching, etc).  There are also helper classes for common functions (loading localized language files, creating notifications in TouchSmart, sending requests to TouchSmart, etc).  Check the SDK for details and feel free to send any questions my way.

If you aren’t developing using WPF, it includes all of the information you need in order to create an application without the library.

Sound off in the comments any ideas you have for apps, as well as your interest in TouchSmart development.

Year’s End: Changes, Changes…

At the end of 2008, I reflected on the many major events that took place within the shortness of summer. I graduated, got married, moved 1700 miles from home, and started my career at HP. After settling into California life, my wife and I began to explore the area, meet new friends, and let life slow down a little. This year looked to be piece of cake.

We then decided that, given that the economy was driving down housing cost, we would look into purchasing our first home.  We quickly learned all that we needed to know about real estate to complete a purchase, as well as just how much more expensive California is, when compared to Kansas.

After moving into our new home, we decided to make it our own by doing some renovations.  Suddenly, our nearest hardware store became a fun place for inspiration and supplies, and we were completely in over our heads in terms of the scope of our projects, some of which still have yet to be completed.

We also decided to throw in a new dog, a golden retriever named Ecco.  He’s turned out to be quite the handful, granting him the nickname “Marley Dog.”  We’re starting to get a handle on him, but I’m still missing a few pairs of socks, and our carpet is quite the worse for wear.

Finally, we decided that a new home, renovations, and a dog weren’t enough and are now expecting our first child – a girl.  We’re preparing our home for a rugrat, and I’m going to have to look into getting a shotgun so that I can practice my shooting before she brings any boys home.

No, things are not slowing down in the least.  Given that a child is on the way, things are likely just ramping up.

Professionally, this year has been just as hectic.  I’ve now been an HP employee for 1.5 years, and have a few shipped products under my belt (more on those in another post).  Being that they coincided with the release of Windows 7, many late nights were involved to ensure that everything made the Windows 7 RTM date.  Of course, this was all done far before Windows 7 hit the shelves in October, and I’ve since been occupied with patches (more late nights for that), as well as some pretty cool new things.  I’m very thankful for a job in this climate and even more thankful that I find mine interesting.

In 2008, I started a blog as a means to slowly build up content for a website primarily focused on presenting employers a place to learn about me.  You might be familiar with this blog, considering that you are reading it right now.  I’ve come to a few realizations in the year that I’ve been writing:

  1. Much to my surprise, I’ve been able to interest some people with some of the information I’ve put out here.
  2. I had forgotten how much I enjoy writing and expressing my thoughts.

Due to these realizations, I’ll be focusing my content to better help those that stumble upon this blog, as well as begin to expand on the topics I write about.  Don’t worry – I’ll stay focused on the two things I know best: software development and video games; however, I’d like to move into a few new aspects of both.  I’ll also try to better encourage my readers to participate in a discussion, rather than digest and move on.

In light of both of those statements, do any of you have topics you’d like me to delve into?  Come on, you quiet bunch, start talking!  I only make you log in to make sure my comments aren’t filled with Viagra commercials.

I hope all of you have had a good year, and wish you a good one to come.  I hope that my writing has been helpful or interesting to you in some way, and appreciate your support!

In addition to topic suggestions, feel free to add the musings of your past year.  I’d love to hear how everyone else is doing.

Multithreading in WPF

If you’re unfamiliar with multithreading, be sure to check out my previous entries on the topic.

In WPF, creating a thread is as easy as it is with C#. You can find an example on that here.  Alternatively, you could use the BackgroundWorker, which basically will create a thread and will give you a generalized, simplified interface in which to interact with it for a common threading task: doing an extra task in the background (such as downloading or progress bar updating).

In an earlier post, I used a mysterious method to enable responsiveness in the UI while loading a bunch of content (in that case, images).

This mystical object is called The Dispatcher.


No, this isn’t an edge-of-your-seat thrill ride movie that smacks explosions, swords, and alien guts into your M&M-filled mouth. It is an object used to manage the work for threads within WPF.  It maintains a queue of work items that are requested of any given thread, based on their order and priority.  This is the object you want to get to know if you’re going to be playing with your UI on a separate thread.

As mentioned previously, UI objects can’t be accessed outside of the threads that created them.  You can, however, use a separate thread to determine what changes you’ll be making and to what objects you will make them, then use their thread to actually apply that change.  In order to do this, use the object’s dispatcher to schedule the work on their queue.

For example, take a look at the code for loading images mentioned above:

private void LoadImage(string fname)
	// instantiate and initialize the image source
	BitmapImage bmi = new BitmapImage();
	bmi.UriSource = new Uri(fname, UriKind.Relative);
	bmi.Freeze();		// freeze the image source, used to move it across the thread
	// this method tells the separate thread to run the following method to run on the UI thread
	// the (ThreadStart)delegate(){ } notation is a shorthand for creating a method and a delegate for that method
	TheImage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate ()
		TheImage.Source = bmi;

This method creates the BitmampImage object on a separate thread, leaving the main thread free for user input, and freezes it so that it can be used on another thread.  It then uses TheImage’s Dispatcher to modify TheImage on its own thread by calling its dispatcher’s BeginInvoke method.

There are two ways to invoke using the dispatcher: BeginInvoke() and Invoke().  BeginInvoke() will queue the work for the dispatcher and continue the separate thread’s execution.  It puts in the request for the UI thread to execute the delegate, then continues on it merry way for its own execution.  This is useful when your separate thread does not rely on what it is requesting the UI thread to do.

The Invoke() method will wait until the delegate is executed and returns.  If you are modifying anything that you need or if the modification must be done before continuing in the separate thread, you should go with this one.

The Dispatcher is something you’ll get pretty cozy with if you plan on changing your UI elements from a separate thread.  If you’re just doing a progress bar or something else that is rather predictable, you can skip it by using the BackgroundWorker’s ReportProgress method and ProgressChanged event.  Just be sure to give it some time if you are calling the dispatcher often.

In case you didn’t notice all of my linking to previous posts, you may want to check out the rest of my posts on multithreading.

Threading Complexities

As I explained previously, threads are like workers with separate to-do lists that share the same tools and materials and perform tasks at the same time. There are a couple of tough situations that these coworkers will often find themselves in, however, and you need to make sure that their employer has the proper processes to provide solutions.  Yes, I am going to run this metaphor straight into the ground.

First, you need to know what “concurrent” means to a computer. defines it as “occurring or existing simultaneously or side by side”.  Your computer, however, defines it as “switching between the tasks fast enough so that nobody notices that they aren’t occurring simultaneously”.  So, when I say that your employees are working at the same time, I actually mean that they are working one at a time but switching between who is working fast enough that the boss doesn’t realize they’re taking breaks.  The CPU is constantly juggling which thread gets to execute, based on priority and (usually) the order by which they come.  This same kind of exercise is happening with all of the processes that are currently running.

If you don’t notice, why should you care?  Well, there is a delay when switching between threads (or processes) called a context switch.  During a context switch, the CPU must save the state of the currently active thread, choose the next thread to give time to, restore that thread’s state, and continue its execution.  What this boils down to is that there is cost a  associate with multithreading.  You need to be aware of this cost, otherwise you may find your application running slower with multiple threads.  The reason is that your threads are unbalanced – that they are switching back and forth so much that the time it takes to do all of the context switching is greater than the time you save running two tasks simultaneously!

I ran into an example of this recently when attempting to improve the responsiveness of an application.  I was trying to do things on a separate thread to keep things smooth in the UI for the user; however I had to perform a task on a set of elements on the original thread (more on that later).  This forced me to call back to the original thread so often that the experience ended up being even worse.  I’ll explain more detail about how that works in WPF in a future post, but here’s the basic idea in pseudocode:

create a new thread to perform a CPU-intensive task; run:
   foreach object in somelist
      call back to original thread with the following task:
         perform an action on object

Because I went back to the original thread so often and so quickly, the CPU was spending most of its time context switching.  In order to fix it, I added one line:

create a new thread to perform a CPU-intensive task; run:
   foreach object in somelist
      call back to original thread with the following task:
         perform an action on object
      sleep for x amount of time

I added a sleep command in the separate thread.  This gave the main thread time to perform the task on the object, redraw, and settle in a little before I gave it another task.  This added a visual delay to the action on-screen (since there is x amount of time between each object being acted upon), but that was acceptable in this case to give the user a smooth experience.

Secondly, there is a key part of this metaphor that you have to consider: each worker is sharing resources.  This is good – it means that each thread can access the data it needs while executing; however, it comes with a caveat: you have to ensure no thread is changing that data while another thread is trying to access it.

Imagine if we have two workers sharing a drill.  Worker One is going to use it to screw a shelf to a wall, while Worker Two is going to drill a hole for the next shelf.  Now, imagine that Worker One has placed the screw where he wants it and is about to pull the trigger on the drill when a context switch occurs.  Worker One freezes, and Worker Two grabs the drill.  He pulls out the Phillips head bit that Worker One was using and replaces it with a drill bit.  Like an episode of Seinfeld, the worst thing happens at the worst possible time: another context switch.  Worker one takes the drill back and uses the drill bit on his screw, damaging the screw and quite possibly his hand.  This is called a race condition: multiple independent algorithms are dependent on a single shared resource, thus making the timing of each access of that resource critical to the success of each algorithm.

This means you have to be weary of using your global variables or the members of your class in a thread.  You must be certain that you aren’t changing something that your other thread is depending on.  The common way to handle this is by using mutual exclusion (or mutex) algorithms.  The basic concept is that, when using a variable that is common to other threads, you must ensure that the variable is not currently in use by another thread, often via queues or access flags.  Take a look at the previous link for a list of well-known algorithms with examples.  There is a wealth of knowledge related to solving race conditions, and I’m not even going to attempt to address it all.

If you take a close look at the pseudo code above, you’ll notice that I’m using a single thread to perform all actions on the set of objects, thus avoiding race conditions (as only one thread accesses them at a time).  This isn’t by my own design, however; this is a restriction given to UI elements in most, if not all, languages.  Because of their nature, UI elements aren’t thread safe.  They can be accessed by you, the graphics engine, or even the user.  Because of the amount of overhead required to allow UI elements to work in threads, they are restricted to being accessed only by the thread that created them.  Above, since I cannot access the UI elements in my worker thread, I have to call back to the thread that created the object and tell it to do the modifications I need.  This makes moving work to separate threads in a UI-heavy application complicated at times, but you get used to it pretty quickly.

So, it doesn’t sound near as simple as it did in my first post; however, don’t let this scare you away from using multithreading.  Once you get the hang of it, it is really quite simple to use.  Besides, you’ll need to be familiar with it before digging your hands into any serious user-oriented application.

Just a Bit: Make Your WPF Application Resolution and DPI Independent

We’ve all seen it. Lower your resolution to 800×600? The application’s UI is giant, hard to navigate, and ugly. Bring it up to 1920×1200? Now, you can’t see it. Here’s an easy way to make your application’s content size relative to your window’s size (which will lead it to size independently of the resolution or DPI).

All you have to do is surround your content in a Viewbox, with a uniform Stretch (to ensure the aspect ratio is maintained). You may need to specify a particular size for your content, in order to ensure proper aspect ratio and distance for your elements.

<Viewbox Stretch="Uniform">
    <Grid Width="800" Height="600">
        <!-- Content -->

Introduction to Threads

Threading is a pretty core concept, but I felt it might be necessary to give it a brief explanation before moving on to some WPF-specific concerns for threads.  If you are already familiar with threads, these aren’t the droids you’re looking for.

If you think about the flow of a simple application that does not use multithreading, you’ll find that you can basically draw a line on a sheet of paper and label the events of the process as a straight line of consecutive actions:

simple_console_eventsThis method is often very stifling to the developer, as it limits what you can do.  At times, you want another action to be able to perform simultaneously.  A classic case is to allow a user to cancel an action.  In this case, the user is allowed to interact with the process while it is busy.  That is, the line of execution cannot be drawn so straight:

Threaded ExecutionYou can perform this (seemingly) concurrent operation by using threads.  Threads are similar to processes in that they are a set of instructions for the computer to perform; however, processes and threads differ in that separate threads share resources under the same process, while processes are independent of each other.  You can think of separate threads as workers who share materials and tools, but have separate instructions to perform at the same time.

Every application has at least one thread: the main thread of execution.  This is represented by the green line above; it is the thread that starts the application and is the top of the family tree of the cute little baby threads that are spawned during your application’s execution.  When you have an action that you wish to perform concurrently with the main thread, you create a new thread, give it a set of tasks, and start its execution.  In C#, simply instantiate a Thread object using a delegate and start it.

Thread worker = new Thread(delegate()
      // actions to perform on separate thread

A delegate is a reference type to a function that serves to give the thread an action to perform. So, if you think of a thread as a worker separate from the main thread, you can think of a delegate as that worker’s to-do list.

In C#, there is also a Delegate class. This class is used as a base for derived delegates – you can use this if you want to have a custom delegate, which is useful for defining to-do lists that have specific requirements. For example, events use custom delegates in order to ensure that the event handler has the proper information when it reacts to the event. So, if you want to create a MouseDown event handler, you must define a handler that accepts the sender of the event, as well as information regarding the mouse’s state.

Seems simple enough, right?  Well, things can actually get quite complicated.  I’ll address some complexities of multithreading in another post.