IN THIS TASK
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
- The Visual C# programming language
- Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
- Create a new Visual C# Windows Application project named PoolDemo.
- Use the Toolbox to add a Button control to the form. The default name for the Button control is button1.
- Right-click the form, and then click View Code.
- Paste the following using directive after the existing using directives, but before the declaration of the PoolDemo namespace:
- 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);
- 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);
- Press CTRL+F5 to run the application.
- 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 articolo: 315460 - Ultima revisione: 11 lug 2008 - Revisione: 1