在.NET中,有什么线程将事件在处理? [英] In .NET, what thread will Events be handled in?

查看:124
本文介绍了在.NET中,有什么线程将事件在处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#实现生产者/消费者模式。我有一个消费者线程监视共享队列和生产者线程放置物品到共享队列。生产者线程订阅接收数据...也就是说,它有一个事件处理程序,只是坐在那里,等待一个昂达触发事件,(数据是从第三方的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.

在昂达事件不火的制作人,我已经预料到我的生产者线程来处理。但是,这似乎不是发生了什么。在昂达事件仿佛它正在一个新的线程来处理,而不是!请问这是怎么.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
    }
}

和那么你已经有了一个消费者线程,拉东西了该队列。问题是,昂达事件是由你的 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#事件是基本上只是一个易于使用的收集代表和射击事件只是导致运行时遍历所有与会代表和火他们一次。

C# events 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.

所以,你的昂达事件处理函数获取调用对任何线程的 ExternalSource 正在运行。

So your OnData event handler is getting called on whatever thread the ExternalSource is running on.

这篇关于在.NET中,有什么线程将事件在处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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