以下三个代码示例演示 QueueUserWorkItem 和 RegisterWaitForSingleObject 方法。第一个示例将一个由 ThreadProc 方法表示的非常简单的任务排入队列,使用的是 QueueUserWorkItem。
[C#]
using System;
using System.Threading;
public class Example {
public static void Main() {
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
static void ThreadProc(Object stateInfo) {
Console.WriteLine("Hello from the thread pool.");
}
}
为 QueueUserWorkItem 提供任务数据
以下代码示例用 QueueUserWorkItem 将一个任务排队并为该任务提供数据。
[C#]
using System;
using System.Threading;
public class TaskInfo {
public string Boilerplate;
public int Value;
public TaskInfo(string text, int number) {
Boilerplate = text;
Value = number;
}
}
public class Example {
public static void Main() {
TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);
if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
else {
Console.WriteLine("Unable to queue ThreadPool request.");
}
}
static void ThreadProc(Object stateInfo) {
TaskInfo ti = (TaskInfo) stateInfo;
Console.WriteLine(ti.Boilerplate, ti.Value);
}
}
RegisterWaitForSingleObject
下面的示例演示了几种线程处理功能。
使用 RegisterWaitForSingleObject 将需要执行的任务以 ThreadPool 线程的方式排队。
使用 AutoResetEvent 发出信号,通知执行任务。
用 WaitOrTimerCallback 委托处理超时和信号。
用 RegisteredWaitHandle 取消排入队列的任务。
[C#]
using System;
using System.Threading;
public class TaskInfo {
public RegisteredWaitHandle Handle = null;
public string OtherInfo = "default";
}
public class Example {
public static void Main(string[] args) {
AutoResetEvent ev = new AutoResetEvent(false);
TaskInfo ti = new TaskInfo();
ti.OtherInfo = "First task";
ti.Handle = ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(WaitProc),
ti,
1000,
false
);
Thread.Sleep(3100);
Console.WriteLine("Main thread signals.");
ev.Set();
Thread.Sleep(1000);
}
public static void WaitProc(object state, bool timedOut) {
TaskInfo ti = (TaskInfo) state;
string cause = "TIMED OUT";
if (!timedOut) {
cause = "SIGNALED";
if (ti.Handle != null)
ti.Handle.Unregister(null);
}
Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
ti.OtherInfo,
Thread.CurrentThread.GetHashCode().ToString(),
cause
);
}
}