In .NET, what thread will Events be handled in?

后端 未结 4 961
既然无缘
既然无缘 2020-12-08 13:17

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 sha

相关标签:
4条回答
  • 2020-12-08 13:29

    Raising an event with Invoke is the same as calling a method - it gets executed in the same thread you raised it.

    Raising an event with BeginInvoke uses ThreadPool. Here are some minor details

    0 讨论(0)
  • 2020-12-08 13:37

    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
        }
    }
    

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

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

    0 讨论(0)
  • 2020-12-08 13:42

    you have to use autoresetevent handlers for this problem.....in autoresetevent when producer produses it set the signal then consumer reset its signal and consume.. after consuming consume set signal then only producer produced...

    AutoResetEvent pro = new AutoResetEvent(false);
    AutoResetEvent con = new AutoResetEvent(true);
    
    public void produser()
    {
    
        while(true)
        {
            con.WaitOne();
    
            pro.Set();
        }
    }
    
    public void consumer()
    {
        while (true)
        {
        pro.WaitOne();
           .................****
    
        con.Set();
        }
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        Thread th1 = new Thread(produser);
        th1.Start();
        Thread th2 = new Thread(consumer);
        th2.Start();
    }
    
    0 讨论(0)
  • 2020-12-08 13:43

    Unless you do the marshaling yourself, an event will execute on whatever thread is invoking it; there's nothing special about the way events are invoked, and your producer thread doesn't have an event handler, your producer thread simply said "hey, when you fire this event, call this function". There's nothing in there that causes the event execution to occur on the attaching thread, nor on its own thread (unless you were to use BeginInvoke rather than invoking the event's delegate normally, but this will just execute it on the ThreadPool).

    0 讨论(0)
提交回复
热议问题