在.NET中并发线程之间传递数据的最好方法是什么? [英] What's the best way to pass data between concurrent threads in .NET?

查看:128
本文介绍了在.NET中并发线程之间传递数据的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程,一个需要轮询一堆独立的静态资源寻找更新。另一个需要获取数据并将其存储在数据库中。如果线程1告诉线程2有东西要处理?

I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process?

推荐答案

如果数据块是独立的,的数据作为要由线程池处理的工作项。使用线程池和 QueueUserWorkItem 将数据发布到线程。您应该使用对称线程池获得更好的可扩展性,并限制生产者和消费者之间必须发生的同步量。

If the pieces of data are independant then treat the pieces of data as work items to be processed by a pool of threads. Use the thread pool and QueueUserWorkItem to post the data to the thread(s). You should get better scalability using a pool of symmetric threads and limiting the amount of synchronisation that has to occur between the producer and consumer(s).

例如(从< a href =http://msdn.microsoft.com/en-us/library/4yd16hza.aspx =nofollow noreferrer> 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); 
}

这篇关于在.NET中并发线程之间传递数据的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆