QueueUserWorkItem()的用法

stevenjin 2008-05-25 12:48:06
在创建线程池时,QueueUserWorkItem()方法将一个任务项排列到线程池中,原型如下:
public static bool QueueUserWorkItem(WaitCallback callBack,object state)
其中,callback表示线程池执行任务时要调用的委托,state表示包含状态的对象,该对象将在线程执行任务时传递给委托。返回值true表明方法调用成功了,false表示调用失败。在MSDN的示例里,我看到了一个new,被搞晕了,它在这里干嘛的呀?这句代码如下:
if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti))

完整代码如下:
// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
using System;
using System.Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo {
// State information for the task. These members
// can be implemented as read-only properties, read/write
// properties with validation, and so on, as required.
public string Boilerplate;
public int Value;

// Public constructor provides an easy way to supply all
// the information needed for the task.
public TaskInfo(string text, int number) {
Boilerplate = text;
Value = number;
}
}

public class Example {
public static void Main() {
// Create an object containing the information needed
// for the task.
TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

// Queue the task and data.
if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {
Console.WriteLine("Main thread does some work, then sleeps.");

// If you comment out the Sleep, the main thread exits before
// the ThreadPool task has a chance to run. ThreadPool uses
// background threads, which do not keep the application
// running. (This is a simple example of a race condition.)
Thread.Sleep(1000);

Console.WriteLine("Main thread exits.");
}
else {
Console.WriteLine("Unable to queue ThreadPool request.");
}
}

// The thread procedure performs the independent task, in this case
// formatting and printing a very simple report.
//
static void ThreadProc(Object stateInfo) {
TaskInfo ti = (TaskInfo) stateInfo;
Console.WriteLine(ti.Boilerplate, ti.Value);
}
}



...全文
4364 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuwen861209 2011-03-18
  • 打赏
  • 举报
回复
WaitCallback是一个委托,new的作用是建立一个WaitCallback类型的委托实例,参数ThreadProc是线程启动时需要进行处理的方法。
gomoku 2008-05-25
  • 打赏
  • 举报
回复
[Quote=引用楼主 stevenjin 的帖子:]
我看到了一个new,被搞晕了,它在这里干嘛的呀?这句代码如下:
if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti))
[/Quote]

The normal way to create a delegate.


//If you write code like this:
ThreadPool.QueueUserWorkItem( ThreadProc, ti));

//Actually the compiler understands it and silently changes it to:
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti));
witer666 2008-05-25
  • 打赏
  • 举报
回复
可以NEW一个构造函数

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧