Raising events asynchronously RRS feed

  • Question

  • I have a C# (.Net 4.5) class which receives TCP data, does some decoding, and fires a MessageReceived event. I have another class which subscribes to this event, and does many things with this data (saves it to the database, sends alarm SMSes and emails if necessary, etc.)

    As far as I understand, when the base class fires the event, and the consuming class acts upon this event, the consuming class will block the thread. Only when it's finished doing what it needs to do, does it return control to the base class. This is obviously a problem as it's blocking the base class from carrying on receiving TCP data.

    Now, the consuming class could do everything it needs to do in a separate thread, which it can spin up and execute when the MessageReceived event is triggered. This would return control to the base class immediately. However, I was wondering if it's not possible for the base class to trigger the event in a separate thread? So that whichever consumer is subscribed to this event, it will be working in a separate thread?

    Is it possible to do something like this in C#? Is this a recommended way of doing things?


    Fabricio Rodriguez - Pretoria, South Africa

    Friday, December 15, 2017 7:25 PM

All replies

  • Microsoft seems to intentionally confuse people. They sometimes use terms in new ways that confuse us. An Event might be the event "keyword" (which is actually a delegate) or it might be an event as in the AutoResetEvent Class.

    Also, you say "base class" but are you sure that is what you mean? Is the consuming class truly derived from the receiving class?

    You can use the AutoResetEvent Class for the one thread to signal the other thread. You can have a queue or buffer or something (whatever you design) of data to be processed. The receiver puts data in and the processor takes data out. You just need to ensure that they both don't access the data at the same time and .Net provides ways to do that, sometimes automatically.

    Sam Hobbs

    Friday, December 15, 2017 11:19 PM