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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With