我有两个线程,一个需要轮询一堆单独的静态资源以查找更新。另一种需要获取数据并将其存储在数据库中。线程1如何告诉线程2有东西要处理?
如果数据块是独立的,则将数据块视为要由线程池处理的工作项。使用线程池和QueueUserWorkItem
将数据发布到线程。您应该使用对称线程池并限制生产者和消费者之间必须发生的同步量来获得更好的可伸缩性。
例如(来自MSDN http://msdn.microsoft.com/en-us/library/4yd16hza.aspx):
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)