Below is the list of Apps delivered by me to the clients.

  • TruthOrDare

    Play the fun game of Truth or dare with friends and family! Perfect fun for Saturday game night that will get everyone in on the action and hilariousness.

    Fun challenging dares and interesting truths. Learn more about your friends and other players than you ever thought you knew! Great for an icebreaker game or just for having fun.            

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare

Truth or Dare










App Store Link for the App –> http://www.windowsphone.com/en-gb/store/app/truthordare/4737969c-57f5-4398-acf5-b7b8fce0138e

  • ZenProverbs

     A Wise Man Once Said: Gain Wisdom from the masters with this collection of zen proverbs. Use them in your daily meditations to achieve enlightenment. Download these proverbs and enhance your  

     spiritual quest today!

Zen Proverbs

Zen Proverbs












Zen Proverbs

Zen Proverbs












Zen Proverbs

Zen Proverbs










App Store Link for the App –> http://www.windowsphone.com/en-gb/store/app/zenproverbs/a421aaea-c469-4350-8aa6-cc884222f491

I will keep this post updating regularly with the apps that are published in app store.




Have a look at latest windows phone application that i developed for a client.


This application makes uses of Accelerometer feature available on Windows Phone.



The source code of the application will be made available on demand and could also be customized if needed.


Any comments and feedback are most welcome.

Lets learn about creating Windows Phone Projects

Visual Studio 2010

    • Visual Studio is an “Integrated Development Environment” for creating programs
      • Edit program source
      • Add and manage program resources
      • Build, deploy and debug an application
      • It can be used for multiple platforms and languages and can also be customized by plug-ins for the different target platforms

Windows Phone on Visual Studio

  • Create the Windows Phone Solution
  • Edit the program source files
  • Add and manage program resources
  • Build and run the solution
  • Debug the solution on emulator or device
  • Manage the properties of deployment in marketplace.

Visual Studio Project and Solutions

  • A .NET Program is made up of assemblies
    • An assembly is a library file(.dll) or an executable (.exe) and it contains compiled code and resources (e.g. images and sounds) along with a manifest.
    • The .exe file also contains an entry point (Main)
  • A Visual Studio solution project describes the content of a single assembly
  • A Visual Studio solution is made up of number of projects and at least one of them has an entry point where a program can start
  • A Visual Studio Solution is an XML file that contains reference to the project file that make up solution.
  • Each project contains resources and code which contains single project can be shared amongst multiple solutions also a library assembly can be used in the library.



  • New projects and solutions are created from templates installed in Visual Studio
  • Additional templates can be installed so that the tool can be used to target different platforms
  • These templates give you the basic structure of the type of program you are trying to make and also add the relevant references and saves you a lot of effort.

Making a Silverlight Application

  • Silverlight apps are generally line of business apps which are used to do business with and there is a template that helps us create a Windows Phone Silverlight application.
  • Very easy to create rich user interface.
  • This creates the initial page for our application and configures Visual Studio to target the Windows Phone platform.
  • If we want to create additional pages and add resources to the solution we can do this using Visual Studio.

Note – Windows Phone Mango is called 7.5 but the tools and the OS is called 7.1. The reason being the development team started pretty early and named the OS as 7.1 (after 7.0) but when the marketing team decided that they would call the whole package as 7.5

XNA Game Projects

  • Could be developed in a similar way to a Silverlight app but the starting template needs to be different.
  • The solution structure will be different though.

  • The content project contains all the elements of the game, assets, texts,etc
  • If you have not developed an XNA games before then i would like tell you that
    • An XNA game will not be like a silverlight app in which you press a button but in an XNA game the stuff will be repeated 30 times a second.
    • Its pain free and very well packaged.
    • XNA is great for writing games
    • Makes good use of graphics acceleration
    • Can be tedious to create UI behaviors

Combining Silverlight & XNA

  • It is possible for the silverlight form containing XNA content to hold silverlight components and this makes it possible to overlay Silverlight UI elements on top of an XNA display.
  • This makes it easier to build interfaces to XNA game.
  • Such a project will contain at least three projects
    • SilverXNA – It is the project that actually does the running
    • SilverXNALib – The libraries
    • SilverXNALibContent – XNA library content which will have assets, etc
    • When we make a silverlight and XNA combined program then we will have a page that will take us from the silverlight to XNA. So shown in the image below we will have a single button that will navigate to the game page on clicking.
    • Also this button click starts the XNA game engine.

  • The XNA page as shown below contains version of
    Draw and Update methods that are called to run the game within the silverlight

Multiple Project Solutions

  • A VS 2010 solution can have
    • PC version of XNA game
    • XBOX version of a game
    • Windows Phone Version of a game
    • They can also share code libraries which are also part of solution
    • Many projects can share the output from a single project.

Running Applications on Windows Phone Platform

Windows Phone Device Basics

To connect from a Windows PC to Windows Phone Device we need the Zune software. this could also

  • Synchronize Media
  • Perform Phone Updates
  • The download is available at http://zune.net
  • Before we deploy our application on Windows Phone we need to register it as a developer device. This registration is a one time process and the registered developers can register up to 3 devices (but registered students can register only one device).
  • Now you need to connect the phone to your PC and from the drop down as shown below we can select the Windows Phone 7 Device

  • The debugging method and development environment is the same for both the WP devices and Emulator.
  • The problems that you might face while deployment might be
    • If the phone is displaying lock screen deployment will fail.
    • Applications that use media will not work correctly if they are deployed when the Zune software is running. To solve this problem we can use “Windows Phone Desktop Pass- Through” program to connect instead of Zune. It is available with SDK.
    • Once the application is deployed it will be stored on the device for later use but remember at a time you can have only 10 of your own applications on the phone at any time. You can anyways send the compiled version of your application to other registered developers for them to use on their developer devices.

Emulator Basics

  • Emulator is available with Windows Phone SDK.
  • It runs as a program on the windows PC.
  • It has the same software as Windows Phone device but is targeted to run on Windows PC platform.
  • The Emulator
    • Has a browser
    • Will provide phone behaviors for things like placing calls and sending SMS. Also it has some entries in phonebook
    • Contains emulation of windows phone camera, GPS and motion sensors
    • Has the ability to capture screenshots of programs running on the phone.
    • If you are developing a game then it is recommended to run it on the phone as the performance is something which is not properly tested on emulator as it running in Windows environment.
    • You can use a PC mouse to touch on the screen.
    • If you have a multitouch monitor then that touch can be passed to the emulator as well.
    • If you want to use the PC keyboard for typing then you should use the Pause/Break key to toggle the emulator keyboard. When the Emulator keyboard is not there it will take the input from PC keyboard.
    • The windows Phone Emulator
      • Does not support Zune media playback.
      • Uses only only the built in browser application.
      • Should be used for functional testing only.
      • When you hover over the emulator with a PC mouse you will see an extra set of tools.
        • These allow you to rotate the emulator into different orientations
        • There are two landscape positions but only one portrait position.

  • The camera can also be emulated but it can take a simple photograph and return it.
  • Location Emulation also works now with Mango version. The location tab is shown below and you can click the location move the emulator to that position and also place pushpins to describe a route and then replay the route as well.

  • Windows Phones contains an accelerometer and compass that can be emulated as well for determining the position.

  • Also you can take screenshots in Windows Phone and the same can be emulated as well

Program Debugging

  • We can add breakpoints
  • We can use Single Stepping
  • We can use the Immediate Window


Your feedback and comments are welcome.



So the topics we are going to cover in this post are:

  • Windows Phone Task Management
  • Multi-Tasking with Background Agents
  • Creating tasks in Visual Studio
  • File Transfer Tasks
  • Background Notifications
  • Background Music Playback Tasks


  • Must have .Net and Silverlight development experience
  • Must have developed a windows phone apps.

Lets start


Windows Phone Task management

Forground Tasks

  • Normally a windows phone application runs in the foreground and interacts with the screen and user of the phone
  • There is only one foreground application active at a time though other may be running but are not active. This ensures better battery life for the user.

Background Tasks

  • A Windows Phone application can have only one background agent which can perform perodic tasks or resource intensive tasks or both.
  • The Agent can run when the application is not in the foreground.
  • The background tasks have limitations to what it can do and processor and other phone facilities. The logical reason that microsoft architect give is that if a background tasks goes out of control or does what it is not intended to do somehow it should not affect the battery life of the phone and the user user experience as well.
  • A background task can be used used to conatc the datbase and get the updates every half an hour or play music from a server online.

Background Agent Health Warning

  • There can only be limited number of background agents running at a point of time and this controlled by the oprating system.
  • A background agent will be started only when the operating system can give the agent processor resource.
  • If the phone goes to power saver mode then the background agents may stop running.
  • Also at any point of time the user can see the background tasks running and can manage them and choose to disable them.
  • So dont put any critical logic in background agent as it may not run. Its like icing on cake.

Multitasking with background agent

Agents and Tasks

  • The Agent is the container that is manged by the operating system and agent is the code that will run.
  • There are two kinds of tasks
    • Perodic
      • Will run every now and then (typicallyevery 30 minutes or so).
      • Intended to perform a task that runs regulary and complts quickly
      • Phone will have of limit on how many of them can be running.
      • Good for location tracking tracking and polling background services.
    • Resource intensive
      • Will run when the phone is in a postion to let them. This means it will run when
        • The phone is connected to mains
        • The phone is connected to Wi Fi
        • The phone is not being used (lock screen is displayed)
      • So if you rellay need this to run you need to made some recomendations to the user so that this resource intensive task runs successfully.
      • A Resource intensive agent can run upto 10 minutes.
      • Good for synchronization with host service, unpacking / preparing services, compressing database.

Dual Purpose Agents

  • An application can run both periodic and resource intensive tasks.
  • Can be achived though single background agent class.
  • When the agent start it can determine in which context it is running and behave appropriatly.

Creating tasks in visual studio

Creating an application

  • Lets Create a captians log application which will be a simple logging application.
    • Users can type log entries which are timestamped and stored in an isolated storage.
    • The tracking feature will be added using background agent.
    • The start tracking button click will fire up the background agent will be track the location of the captain and add it to the log. So the agent will update the position even when the program is not active.

  • Create a Windows Phone application solution and develop the foreground tasks and applications.
  • Add a new project to the application solution which is Windows Phone Scheduled task (VS Template). This will contain code will run when the agent is active.

  • Here is the solution file for the captians log which has got two projects:
    • Captians Log – The Windows Phone Silverlight Project which is the main application.
    • LocationTaskAgent – The background agent to perform the tracking.
  • Solutions may contain differnt projects and when the soltion is build all the assembly file outputs will be combined and sent to the phone.

  • Before this works we need to refernce the LocationTaskAgent Project in Captains Log

  • And when we do this the application manifest file adds a little bit of text to hold the description of the background agent and this is how the background agent is bound to the application. Here is the text added to the application manifest file.

  • So below is the code that will run when the agent wakes up so we need fill this OnInvoke method with our code that the agent will run. At the end to this code we need to call the method notify complete whcih will will notify the runtime system that it is done.

  • The Captains log datafile is shared between the application and agent and the first thing that the agent will do is load this datafile from the isolated storage.

  • Now we make use of GPS traking to find out the current loaction. So we make GeoCoordinateWatcher and start it and use it to get the location. Now before you start thinking about the performance hit this does i would like to tell you that there is a special version of this class provided for Background Agents which uses cached location data which is stored every 15 minutes.

  • And then agent just stores back this location to the application and goes to sleep.

  • Finally a notification is displayed to the user on which the user can click and go to the main application.

File transfer tasks

  • It is possible to create a background task to transfer files to and from application’s isolated storage.
  • The transfer will take place when the application is not running.
  • An application monitor the state of downloads and display their status
  • Files can be transferred from http or https hosts (ftp is not suppoerted currently)
  • The system maintains a queue of active transfers and services each one in turn.
  • Applications can query the state of active transfers.

Background Transfer Policies

  • Policies are :
    • Maximum upload file size is 5Mb
    • Maximum download file size over cellular (mobile phone) data : 20Mb
    • Maximum dowload file size over WiFi : 100Mb
  • These can be modified by settng the value of TransferPreferences on a particular File Transfer.

Background Transfer Namespace

  • The background transfer namespace is :

  • All the background transfer services are provided from the BackgroundTransfer namspace
  • Most instertingly you dont need to create additional projects to manage background transfers.

Create a Background Transfer

  • The following code creates a request and sets the source for transfer and it also sets the transfer method.

  • The following code sets the destination of the files transfer which is isolated storage of the application. Also it sets the preferences for the transfer. Now the transfer preferences can have multiple string so that you can set multiple properties.

  • The following code starts the transfer request by adding it to the list of active transfers. Also catches the exception if any and shows a message if it cannot proceed with the transfer.

  • The following code monitors the transfer by binding the methods to the events fired by the transfer request.


  • You can also kill the transfer by using the following code:

  • Windows phone appplication at any point of time can find out how many active transfers does have and as a rule of thumb you should always check the same whenever your application restarts because your transfers are still running when your application is not active. Below is the code that lets you do the same.

Scheduled Notifications

  • Windows phone app can create scheduled notifications and they are displayed when the application is running or not.
  • When the notification is diplayed the phone user has the option to respond to it or not. Also the notification can be liked to an application page.
  • The notifications can fire once or repeatedly at configurable intervals.
  • The notifications is maintained by phone operating system, once the application can started then it doen not have to do anything.

Sample Application

  • Lets make a simple timer application which will have two silverlight pages.
  • The user will set the time using the slider then preses the start timer button to create a notification.
  • When the notification will fire the 2nd page of the application which is egg ready page will be displayed and if the user clicks on the same then user will be taken to the application.
  • The sceen of the application will look something like this:

  • The code for the creating the reminder is as below. This code will create the reminder and then adds it as a sceduled service. The value eggTime holds the lenght of the delay and this code also sets the url of the page in application.

  • And before you add the reminder you need to check if its already present in the memory and if the that is the case it is removed from the memory. The code for doing that is as below:

Audio Playback Agents

  • It is possible to create a playback that will manage an application playlist and the mechanism is the same as for other background tasks.
  • The audio can be streamed or stored in application’s isolated storage.

  • This would also work pretty much like the things shown above in the post so i am not elaborating it.


You are free to ask any questions or leave your comments here…



The advantage of threading is the ability to create applications that use more than one thread of execution. For example, a process can have a user interface thread that manages interactions with the user and worker threads that perform other tasks while the user interface thread waits for user input.

This tutorial demonstrates various thread activities:

  • Creating and executing a thread
  • Synchronization of threads
  • Interaction between threads
  • Using a thread pool
  • Using a mutex object to protect a shared resource
  • See Threading Sample to download and build the sample files discussed in this tutorial.

    Sample Files


    Example 1: Creating, starting, and interacting between threads

    This example demonstrates how to create and start a thread, and shows the interaction between two threads running simultaneously within the same process. Note that you don’t have to stop or free the thread. This is done automatically by the .NET Framework common language runtime.

    The program begins by creating an object of type Alpha (oAlpha) and a thread (oThread) that references the Beta method of the Alpha class. The thread is then started. TheIsAlive property of the thread allows the program to wait until the thread is initialized (created, allocated, and so on). The main thread is accessed through Thread, and theSleep method tells the thread to give up its time slice and stop executing for a certain amount of milliseconds. The oThread is then stopped and joined. Joining a thread makes the main thread wait for it to die or for a specified time to expire (for more details, see Thread.Join Method). Finally, the program attempts to restart oThread, but fails because a thread cannot be restarted after it is stopped (aborted). For information on temporary cessation of execution, see Suspending Thread Execution.

       1:  // StopJoin.cs
       2:  using System;
       3:  using System.Threading;
       5:  public class Alpha
       6:  {
       8:     // This method that will be called when the thread is started
       9:     public void Beta()
      10:     {
      11:        while (true)
      12:        {
      13:           Console.WriteLine("Alpha.Beta is running in its own thread.");
      14:        }
      15:     }
      16:  };
      18:  public class Simple
      19:  {
      20:     public static int Main()
      21:     {
      22:        Console.WriteLine("Thread Start/Stop/Join Sample");
      24:        Alpha oAlpha = new Alpha();
      26:        // Create the thread object, passing in the Alpha.Beta method
      27:        // via a ThreadStart delegate. This does not start the thread.
      28:        Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
      30:        // Start the thread
      31:        oThread.Start();
      33:        // Spin for a while waiting for the started thread to become
      34:        // alive:
      35:        while (!oThread.IsAlive);
      37:        // Put the Main thread to sleep for 1 millisecond to allow oThread
      38:        // to do some work:
      39:        Thread.Sleep(1);
      41:        // Request that oThread be stopped
      42:        oThread.Abort();
      44:        // Wait until oThread finishes. Join also has overloads
      45:        // that take a millisecond interval or a TimeSpan object.
      46:        oThread.Join();
      48:        Console.WriteLine();
      49:        Console.WriteLine("Alpha.Beta has finished");
      51:        try 
      52:        {
      53:           Console.WriteLine("Try to restart the Alpha.Beta thread");
      54:           oThread.Start();
      55:        }
      56:        catch (ThreadStateException) 
      57:        {
      58:           Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
      59:           Console.WriteLine("Expected since aborted threads cannot be restarted.");
      60:        }
      61:        return 0;
      62:     }
      63:  }

    Example Output

    Thread Start/Stop/Join Sample
    Alpha.Beta is running in its own thread.
    Alpha.Beta is running in its own thread.
    Alpha.Beta is running in its own thread.
    Alpha.Beta has finished
    Try to restart the Alpha.Beta thread
    ThreadStateException trying to restart Alpha.Beta. Expected since aborted threads cannot be restarted.

    Example 2: Synchronizing two threads: a producer and a consumer

    The following example shows how synchronization can be accomplished using the C# lock keyword and the Pulse method of the Monitor object. The Pulse method notifies a thread in the waiting queue of a change in the object’s state (for more details on pulses, see the Monitor.Pulse Method).

    The example creates a Cell object that has two methods: ReadFromCell and WriteToCell. Two other objects are created from classes CellProd and CellCons; these objects both have a method ThreadRun whose job is to call ReadFromCell and WriteToCell. Synchronization is accomplished by waiting for “pulses” from the Monitor object, which come in order. That is, first an item is produced (the consumer at this point is waiting for a pulse), then a pulse occurs, then the consumer consumes the production (while the producer is waiting for a pulse), and so on.

       1:  // MonitorSample.cs
       2:  // This example shows use of the following methods of the C# lock keyword
       3:  // and the Monitor class 
       4:  // in threads:
       5:  //      Monitor.Pulse(Object)
       6:  //      Monitor.Wait(Object)
       7:  using System;
       8:  using System.Threading;
      10:  public class MonitorSample
      11:  {
      12:     public static void Main(String[] args)
      13:     {
      14:        int result = 0;   // Result initialized to say there is no error
      15:        Cell cell = new Cell( );
      17:        CellProd prod = new CellProd(cell, 20);  // Use cell for storage, 
      18:                                                 // produce 20 items
      19:        CellCons cons = new CellCons(cell, 20);  // Use cell for storage, 
      20:                                                 // consume 20 items
      22:        Thread producer = new Thread(new ThreadStart(prod.ThreadRun));
      23:        Thread consumer = new Thread(new ThreadStart(cons.ThreadRun));
      24:        // Threads producer and consumer have been created, 
      25:        // but not started at this point.
      27:        try
      28:        {
      29:           producer.Start( );
      30:           consumer.Start( );
      32:           producer.Join( );   // Join both threads with no timeout
      33:                               // Run both until done.
      34:           consumer.Join( );  
      35:        // threads producer and consumer have finished at this point.
      36:        }
      37:        catch (ThreadStateException e)
      38:        {
      39:           Console.WriteLine(e);  // Display text of exception
      40:           result = 1;            // Result says there was an error
      41:        }
      42:        catch (ThreadInterruptedException e)
      43:        {
      44:           Console.WriteLine(e);  // This exception means that the thread
      45:                                  // was interrupted during a Wait
      46:           result = 1;            // Result says there was an error
      47:        }
      48:        // Even though Main returns void, this provides a return code to 
      49:        // the parent process.
      50:        Environment.ExitCode = result;
      51:     }
      52:  }
      54:  public class CellProd
      55:  {
      56:     Cell cell;         // Field to hold cell object to be used
      57:     int quantity = 1;  // Field for how many items to produce in cell
      59:     public CellProd(Cell box, int request)
      60:     {
      61:        cell = box;          // Pass in what cell object to be used
      62:        quantity = request;  // Pass in how many items to produce in cell
      63:     }
      64:     public void ThreadRun( )
      65:     {
      66:        for(int looper=1; looper<=quantity; looper++)
      67:           cell.WriteToCell(looper);  // "producing"
      68:     }
      69:  }
      71:  public class CellCons
      72:  {
      73:     Cell cell;         // Field to hold cell object to be used
      74:     int quantity = 1;  // Field for how many items to consume from cell
      76:     public CellCons(Cell box, int request)
      77:     {
      78:        cell = box;          // Pass in what cell object to be used
      79:        quantity = request;  // Pass in how many items to consume from cell
      80:     }
      81:     public void ThreadRun( )
      82:     {
      83:        int valReturned;
      84:        for(int looper=1; looper<=quantity; looper++)
      85:        // Consume the result by placing it in valReturned.
      86:           valReturned=cell.ReadFromCell( );
      87:     }
      88:  }
      90:  public class Cell
      91:  {
      92:     int cellContents;         // Cell contents
      93:     bool readerFlag = false;  // State flag
      94:     public int ReadFromCell( )
      95:     {
      96:        lock(this)   // Enter synchronization block
      97:        {
      98:           if (!readerFlag)
      99:           {            // Wait until Cell.WriteToCell is done producing
     100:              try
     101:              {
     102:                 // Waits for the Monitor.Pulse in WriteToCell
     103:                 Monitor.Wait(this);
     104:              }
     105:              catch (SynchronizationLockException e)
     106:              {
     107:                 Console.WriteLine(e);
     108:              }
     109:              catch (ThreadInterruptedException e)
     110:              {
     111:                 Console.WriteLine(e);
     112:              }
     113:           }
     114:           Console.WriteLine("Consume: {0}",cellContents);
     115:           readerFlag = false;    // Reset the state flag to say consuming
     116:                                  // is done.
     117:           Monitor.Pulse(this);   // Pulse tells Cell.WriteToCell that
     118:                                  // Cell.ReadFromCell is done.
     119:        }   // Exit synchronization block
     120:        return cellContents;
     121:     }
     123:     public void WriteToCell(int n)
     124:     {
     125:        lock(this)  // Enter synchronization block
     126:        {
     127:           if (readerFlag)
     128:           {      // Wait until Cell.ReadFromCell is done consuming.
     129:              try
     130:              {
     131:                 Monitor.Wait(this);   // Wait for the Monitor.Pulse in
     132:                                       // ReadFromCell
     133:              }
     134:              catch (SynchronizationLockException e)
     135:              {
     136:                 Console.WriteLine(e);
     137:              }
     138:              catch (ThreadInterruptedException e)
     139:              {
     140:                 Console.WriteLine(e);
     141:              }
     142:           }
     143:           cellContents = n;
     144:           Console.WriteLine("Produce: {0}",cellContents);
     145:           readerFlag = true;    // Reset the state flag to say producing
     146:                                 // is done
     147:           Monitor.Pulse(this);  // Pulse tells Cell.ReadFromCell that 
     148:                                 // Cell.WriteToCell is done.
     149:        }   // Exit synchronization block
     150:     }
     151:  }
    Example Output
    Produce: 1
    Consume: 1
    Produce: 2
    Consume: 2
    Produce: 3
    Consume: 3
    Produce: 20
    Consume: 20


    Example 3: Using a thread pool

    The following example shows how to use a thread pool. It first creates a ManualResetEvent object, which enables the program to know when the thread pool has finished running all of the work items. Next, it attempts to add one thread to the thread pool. If this succeeds, it adds the rest (four in this example). The thread pool will then put work items into available threads. The WaitOne method on eventX is called, which causes the rest of the program to wait until the event is triggered (with the eventX.Set method). Finally, the program prints out the load (the thread that actually executes a particular work item) on the threads.

       1:  // SimplePool.cs
       2:  // Simple thread pool example
       3:  using System;
       4:  using System.Collections;
       5:  using System.Threading;
       7:  // Useful way to store info that can be passed as a state on a work item
       8:  public class SomeState
       9:  {
      10:     public int Cookie;
      11:     public SomeState(int iCookie)
      12:     {
      13:        Cookie = iCookie;
      14:     }
      15:  }
      17:  public class Alpha
      18:  {
      19:     public Hashtable HashCount;
      20:     public ManualResetEvent eventX;
      21:     public static int iCount = 0;
      22:     public static int iMaxCount = 0;
      23:     public Alpha(int MaxCount) 
      24:     {
      25:        HashCount = new Hashtable(MaxCount);
      26:        iMaxCount = MaxCount;
      27:     }
      29:     // Beta is the method that will be called when the work item is
      30:     // serviced on the thread pool.
      31:     // That means this method will be called when the thread pool has
      32:     // an available thread for the work item.
      33:     public void Beta(Object state)
      34:     {
      35:        // Write out the hashcode and cookie for the current thread
      36:        Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(),
      37:           ((SomeState)state).Cookie);
      38:        // The lock keyword allows thread-safe modification
      39:        // of variables accessible across multiple threads.
      40:        Console.WriteLine(
      41:           "HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}",
      42:           HashCount.Count, 
      43:           Thread.CurrentThread.GetHashCode());
      44:        lock (HashCount) 
      45:        {
      46:           if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
      47:              HashCount.Add (Thread.CurrentThread.GetHashCode(), 0);
      48:           HashCount[Thread.CurrentThread.GetHashCode()] = 
      49:              ((int)HashCount[Thread.CurrentThread.GetHashCode()])+1;
      50:        }
      52:        // Do some busy work.
      53:        // Note: Depending on the speed of your machine, if you 
      54:        // increase this number, the dispersement of the thread
      55:        // loads should be wider.
      56:        int iX  = 2000;
      57:        Thread.Sleep(iX);
      58:        // The Interlocked.Increment method allows thread-safe modification
      59:        // of variables accessible across multiple threads.
      60:        Interlocked.Increment(ref iCount);
      61:        if (iCount == iMaxCount)
      62:        {
      63:           Console.WriteLine();
      64:           Console.WriteLine("Setting eventX ");
      65:           eventX.Set();
      66:        }
      67:     }
      68:  }
      70:  public class SimplePool
      71:  {
      72:     public static int Main(string[] args)
      73:     {
      74:        Console.WriteLine("Thread Pool Sample:");
      75:        bool W2K = false;
      76:        int MaxCount = 10;  // Allow a total of 10 threads in the pool
      77:        // Mark the event as unsignaled.
      78:        ManualResetEvent eventX = new ManualResetEvent(false);
      79:        Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);
      80:        Alpha oAlpha = new Alpha(MaxCount);  // Create the work items.
      81:        // Make sure the work items have a reference to the signaling event.
      82:        oAlpha.eventX = eventX;
      83:        Console.WriteLine("Queue to Thread Pool 0");
      84:        try
      85:        {
      86:           // Queue the work items, which has the added effect of checking
      87:           // which OS is running.
      88:           ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),
      89:              new SomeState(0));
      90:           W2K = true;
      91:        }
      92:        catch (NotSupportedException)
      93:        {
      94:           Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");
      95:           W2K = false;
      96:        }
      97:        if (W2K)  // If running on an OS which supports the ThreadPool methods.
      98:        {
      99:           for (int iItem=1;iItem < MaxCount;iItem++)
     100:           {
     101:              // Queue the work items:
     102:              Console.WriteLine("Queue to Thread Pool {0}", iItem);
     103:              ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));
     104:           }
     105:           Console.WriteLine("Waiting for Thread Pool to drain");
     106:           // The call to exventX.WaitOne sets the event to wait until
     107:           // eventX.Set() occurs.
     108:           // (See oAlpha.Beta).
     109:           // Wait until event is fired, meaning eventX.Set() was called:
     110:           eventX.WaitOne(Timeout.Infinite,true);
     111:           // The WaitOne won't return until the event has been signaled.
     112:           Console.WriteLine("Thread Pool has been drained (Event fired)");
     113:           Console.WriteLine();
     114:           Console.WriteLine("Load across threads");
     115:           foreach(object o in oAlpha.HashCount.Keys)
     116:              Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]);
     117:        }
     118:        return 0;
     119:     }
     120:  }

    Example Output

    Note The following output will vary from one computer to another.

    Thread Pool Sample:
    Queuing 10 items to Thread Pool
    Queue to Thread Pool 0
    Queue to Thread Pool 1
    Queue to Thread Pool 9
    Waiting for Thread Pool to drain
     98 0 :
    HashCount.Count==0, Thread.CurrentThread.GetHashCode()==98
     100 1 :
    HashCount.Count==1, Thread.CurrentThread.GetHashCode()==100
     98 2 :
    Setting eventX
    Thread Pool has been drained (Event fired)
    Load across threads
    101 2
    100 3
    98 4
    102 1

    Example 4: Using the Mutex object

    You can use a mutex object to protect a shared resource from simultaneous access by multiple threads or processes. The state of a mutex object is either set to signaled, when it is not owned by any thread, or nonsignaled, when it is owned. Only one thread at a time can own a mutex object. For example, to prevent two threads from writing to shared memory at the same time, each thread waits for ownership of a mutex object before executing the code that accesses the memory. After writing to the shared memory, the thread releases the mutex object.

    This example demonstrates how to use the classes Mutex, AutoResetEvent, and WaitHandle in processing threads. It also demonstrates the methods used in processing the mutex object.

       1:  // Mutex.cs
       2:  // Mutex object example
       3:  using System;
       4:  using System.Threading;
       6:  public class MutexSample
       7:  {
       8:     static Mutex gM1;
       9:     static Mutex gM2;
      10:     const int ITERS = 100;
      11:     static AutoResetEvent Event1 = new AutoResetEvent(false);
      12:     static AutoResetEvent Event2 = new AutoResetEvent(false);
      13:     static AutoResetEvent Event3 = new AutoResetEvent(false);
      14:     static AutoResetEvent Event4 = new AutoResetEvent(false);
      16:     public static void Main(String[] args)
      17:     {
      18:        Console.WriteLine("Mutex Sample ...");
      19:        // Create Mutex initialOwned, with name of "MyMutex".
      20:        gM1 = new Mutex(true,"MyMutex");
      21:        // Create Mutex initialOwned, with no name.
      22:        gM2 = new Mutex(true);
      23:        Console.WriteLine(" - Main Owns gM1 and gM2");
      25:        AutoResetEvent[] evs = new AutoResetEvent[4];
      26:        evs[0] = Event1;    // Event for t1
      27:        evs[1] = Event2;    // Event for t2
      28:        evs[2] = Event3;    // Event for t3
      29:        evs[3] = Event4;    // Event for t4
      31:        MutexSample tm = new MutexSample( );
      32:        Thread t1 = new Thread(new ThreadStart(tm.t1Start));
      33:        Thread t2 = new Thread(new ThreadStart(tm.t2Start));
      34:        Thread t3 = new Thread(new ThreadStart(tm.t3Start));
      35:        Thread t4 = new Thread(new ThreadStart(tm.t4Start));
      36:        t1.Start( );   // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)
      37:        t2.Start( );   // Does Mutex.WaitOne(Mutex gM1)
      38:        t3.Start( );   // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)
      39:        t4.Start( );   // Does Mutex.WaitOne(Mutex gM2)
      41:        Thread.Sleep(2000);
      42:        Console.WriteLine(" - Main releases gM1");
      43:        gM1.ReleaseMutex( );  // t2 and t3 will end and signal
      45:        Thread.Sleep(1000);
      46:        Console.WriteLine(" - Main releases gM2");
      47:        gM2.ReleaseMutex( );  // t1 and t4 will end and signal
      49:        // Waiting until all four threads signal that they are done.
      50:        WaitHandle.WaitAll(evs); 
      51:        Console.WriteLine("... Mutex Sample");
      52:     }
      54:     public void t1Start( )
      55:     {
      56:        Console.WriteLine("t1Start started,  Mutex.WaitAll(Mutex[])");
      57:        Mutex[] gMs = new Mutex[2];
      58:        gMs[0] = gM1;  // Create and load an array of Mutex for WaitAll call
      59:        gMs[1] = gM2;
      60:        Mutex.WaitAll(gMs);  // Waits until both gM1 and gM2 are released
      61:        Thread.Sleep(2000);
      62:        Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");
      63:        Event1.Set( );      // AutoResetEvent.Set() flagging method is done
      64:     }
      66:     public void t2Start( )
      67:     {
      68:        Console.WriteLine("t2Start started,  gM1.WaitOne( )");
      69:        gM1.WaitOne( );    // Waits until Mutex gM1 is released
      70:        Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
      71:        Event2.Set( );     // AutoResetEvent.Set() flagging method is done
      72:     }
      74:     public void t3Start( )
      75:     {
      76:        Console.WriteLine("t3Start started,  Mutex.WaitAny(Mutex[])");
      77:        Mutex[] gMs = new Mutex[2];
      78:        gMs[0] = gM1;  // Create and load an array of Mutex for WaitAny call
      79:        gMs[1] = gM2;
      80:        Mutex.WaitAny(gMs);  // Waits until either Mutex is released
      81:        Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
      82:        Event3.Set( );       // AutoResetEvent.Set() flagging method is done
      83:     }
      85:     public void t4Start( )
      86:     {
      87:        Console.WriteLine("t4Start started,  gM2.WaitOne( )");
      88:        gM2.WaitOne( );   // Waits until Mutex gM2 is released
      89:        Console.WriteLine("t4Start finished, gM2.WaitOne( )");
      90:        Event4.Set( );    // AutoResetEvent.Set() flagging method is done
      91:     }
      92:  }

    Sample Output

    Mutex Sample ...
     - Main Owns gM1 and gM2
    t1Start started,  Mutex.WaitAll(Mutex[])
    t2Start started,  gM1.WaitOne( )
    t3Start started,  Mutex.WaitAny(Mutex[])
    t4Start started,  gM2.WaitOne( )
     - Main releases gM1
    t2Start finished, gM1.WaitOne( ) satisfied
    t3Start finished, Mutex.WaitAny(Mutex[])
     - Main releases gM2
    t1Start finished, Mutex.WaitAll(Mutex[]) satisfied
    t4Start finished, gM2.WaitOne( )
    ... Mutex Sample