问题描述
我尝试在 C# 中实现生产者/消费者模式.我有一个监视共享队列的消费者线程和一个将项目放入共享队列的生产者线程.生产者线程被订阅以接收数据......也就是说,它有一个事件处理程序,并且只是坐在那里等待 OnData 事件触发(数据是从第 3 方 api 发送的).当它获取数据时,它会将其放在队列中,以便消费者可以处理它.
I have attempted to implement a producer/consumer pattern in c#. I have a consumer thread that monitors a shared queue, and a producer thread that places items onto the shared queue. The producer thread is subscribed to receive data...that is, it has an event handler, and just sits around and waits for an OnData event to fire (the data is being sent from a 3rd party api). When it gets the data, it sticks it on the queue so the consumer can handle it.
当 OnData 事件在生产者中触发时,我原以为它会由我的生产者线程处理.但这似乎不是正在发生的事情.OnData 事件似乎是在一个新线程上处理的!.net 总是这样工作吗?事件是在自己的线程上处理的吗?我可以控制引发事件时哪个线程将处理事件吗?如果几乎同时引发数百个事件会怎样……每个事件都有自己的线程吗?
When the OnData event does fire in the producer, I had expected it to be handled by my producer thread. But that doesn't seem to be what is happening. The OnData event seems as if it's being handled on a new thread instead! Is this how .net always works...events are handled on their own thread? Can I control what thread will handle events when they're raised? What if hundreds of events are raised near-simultaneously...would each have its own thread?
推荐答案
重新阅读问题后,我想我现在明白了问题所在.你基本上得到了这样的东西:
After re-reading the question, I think I understand the problem now. You've basically got something like this:
class Producer
{
public Producer(ExternalSource src)
{
src.OnData += externalSource_OnData;
}
private void externalSource_OnData(object sender, ExternalSourceDataEventArgs e)
{
// put e.Data onto the queue
}
}
然后你有一个消费者线程从队列中拉出东西.问题是 OnData 事件是由您的 ExternalSource
对象触发的 - 在它碰巧运行的任何线程上.
And then you've got a consumer thread that pulls stuff off that queue. The problem is that the OnData event is fired by your ExternalSource
object - on whatever thread it happens to be running on.
C# event
基本上只是一个易于使用的委托集合,触发"事件只会导致运行时循环遍历所有委托并一次触发一个.
C# event
s are basically just an easy-to-use collection of delegates and "firing" an event just causes the runtime to loop through all of the delegates and fire them one at a time.
因此,您的 OnData 事件处理程序将在 ExternalSource
正在运行的任何线程上被调用.
So your OnData event handler is getting called on whatever thread the ExternalSource
is running on.
这篇关于在 .NET 中,事件将在哪个线程中处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!