skb*_*skb 4 .net concurrency multithreading
我有两个线程,一个需要轮询一堆独立的静态资源来寻找更新.另一个需要获取数据并将其存储在数据库中.线程1如何告诉线程2有什么要处理的?
如果数据片段是独立的,则将数据片段视为要由线程池处理的工作项.使用线程池并将QueueUserWorkItem数据发布到线程.您应该使用对称线程池来获得更好的可伸缩性,并限制生产者和消费者之间必须发生的同步量.
例如(来自MSDN):
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1492 次 |
| 最近记录: |