Learn how to execute a task using a thread from the runtime’s thread pool.
First, Declare a method containing the code you want to execute.
The method’s signature must match that defined by the System.Threading.WaitCallback delegate.
It must return void and take a single object argument.
Call the static method QueueUserWorkItem of the System.Threading.ThreadPool class, passing it your method name.
The runtime will queue your method and execute it when a thread-pool thread becomes available.
The following example demonstrates how to use the ThreadPool class to execute a method named GetData.
First, Declare a method containing the code you want to execute.
The method’s signature must match that defined by the System.Threading.WaitCallback delegate.
It must return void and take a single object argument.
Call the static method QueueUserWorkItem of the System.Threading.ThreadPool class, passing it your method name.
The runtime will queue your method and execute it when a thread-pool thread becomes available.
The following example demonstrates how to use the ThreadPool class to execute a method named GetData.
using System;
using System.Threading;
namespace Thread_Pool_Demo
{
class Program
{
public static void Main(string[] args)
{
// Execute GetData using the thread pool and no arguments.
ThreadPool.QueueUserWorkItem(GetData);
// Create a MessageInfo object to pass to the GetData method.
Chat info = new Chat("Hi, thread pool example");
// Set the max number of threads.
ThreadPool.SetMaxThreads(2, 2);
// Execute GetData using the thread pool and providing an
// argument.
ThreadPool.QueueUserWorkItem(GetData, info);
// Wait to continue.
Console.WriteLine("Main method complete. Press Enter.");
Console.ReadLine();
}
public static void GetData(object state)
{
// Safely cast the state argument to a MessageInfo object.
Chat config = state as Chat;
// If the config argument is null, no arguments were passed to
// the ThreadPool.QueueUserWorkItem method; use default values.
if (config == null)
{
// Display a fixed message to the console three times.
for (int count = 0; count < 3; count++)
{
Console.WriteLine("A thread pool example " + count);
// Sleep for the purpose of demonstration. Avoid sleeping
// on thread-pool threads in real applications.
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}
else
{
for (int count = 0; count < 10; count++)
{
Console.WriteLine(config.Message + " " + count);
// Sleep for the purpose of demonstration. Avoid sleeping
// on thread-pool threads in real applications.
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}
}
}
public class Chat
{
private string message;
// A constructor that takes configuration settings for the thread.
public Chat(string message)
{
this.message = message;
}
// Properties to retrieve configuration settings.
public string Message { get { return message; } }
}
}
0 comments:
Post a Comment