Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run event handler in one permanent thread

I have looked for solution, but found nothing.

In some class i have event

public class ClassWithEvent
{
    public event Action<string> SomeEvent;

    ...
}

and this event has subscriber

public class SubscriberClass
{
    public void SomeMethod(string value)
    {
        ...
    }
}

ClassWithEvent objectWithEvent = new ClassWithEvent();

SubscriberClass subscriberObject = new SubscriberClass();

objectWithEvent.SomeEvent += subscriberObject.SomeMethod;

Somewhere in main thread this event can be invoked.

if(SomeEvent != null)
    SomeEvent(someString);

And when it is happened its handler has to run in second thread. But every time in the same thread, so this second thread has to be permanent and not be terminated after first execution.

Help me please to implement this.

like image 650
Sergey Avatar asked Jul 03 '26 20:07

Sergey


1 Answers

Create a shared queue:

private BlockingCollection<string> queue = new BlockingCollection<string>();

Create your dedicated thread:

Thread thread = new Thread(HandleEvents);
thread.Start();

Process events on that thread:

private void HandleEvents()
{
    foreach (string someValue in queue.GetConsumingEnumerable()) 
    { 
        //Do stuff 
    }
}

Place items into the queue when the event is raised:

objectWithEvent.SomeEvent += (x) => queue.Add(x);

On shutdown complete the queue:

queue.CompleteAdding();
like image 157
Zer0 Avatar answered Jul 05 '26 11:07

Zer0