How to submit a work item to the thread pool by using Visual C#

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Threading



This step-by-step article shows you how to submit a method to the thread pool for execution.

In the .NET environment, each process has a thread pool that you can use to run methods asynchronously.


The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
This article assumes that you are familiar with the following topics:

  • The Visual C# programming language

Create a Visual C# Application that Uses the Thread Pool

  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. Create a new Visual C# Windows Application project named PoolDemo.
  3. Use the Toolbox to add a Button control to the form. The default name for the Button control is button1.
  4. Right-click the form, and then click View Code.
  5. Paste the following using directive after the existing using directives, but before the declaration of the PoolDemo namespace:
    using System.Threading;
  6. Switch back to Design view, and then double-click button1. Paste the following code in the button1_Click event handler:
    private void button1_Click(object sender, System.EventArgs e)
    WaitCallback wcb = new WaitCallback(GetSysDirSize);
    MessageBox.Show("The work item has been placed on the queue");
    catch (Exception ex)
    MessageBox.Show("Error: " + ex.Message);
  7. Paste the following code within the body of the Form1 class. The GetSysDirSize method calculates the total number of bytes that are stored in the system directory. GetSysDirSize calls another method named DirSize to perform the calculation.

    NOTE: This task might take some time to run.
    private void GetSysDirSize(object state)
    long total_length = DirSize(Environment.SystemDirectory);
    this.Text = total_length.ToString();

    private long DirSize(string path)
    long sz = 0;
    System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(path);

    // List files.
    foreach(System.IO.FileInfo f in d.GetFiles())
    sz += f.Length;

    // Recurse into directories.
    foreach(System.IO.DirectoryInfo dx in d.GetDirectories())
    sz += DirSize(dx.FullName);

    return sz;

Test the Sample

  1. Press CTRL+F5 to run the application.
  2. When the form appears, click the button. When the The work item has been placed on the queue message box appears, click OK to dismiss the message box and return to the main form. After a short delay, the total file size in the system directory is displayed in the caption of the form. The length of the delay depends on the speed of your computer and the number of files in the system directory. The calculation of file sizes takes place on a thread in the thread pool.

Id. de artículo: 315460 - Última revisión: 11 jul. 2008 - Revisión: 1