I have some code using Rx, called from multiple threads that does:
subject.OnNext(value); // where subject is Subject<T>
I want the values to be processed in the background, so my subscription is
subscription = subject.ObserveOn(Scheduler.TaskPool).Subscribe(value =>
{
// use value
});
I don’t really care which threads handle values coming out of the Observable, as long as the work is put into the TaskPool and doesn’t block the current thread. However, my use of ‘value’ inside my OnNext delegate is not thread safe. At the moment, if a lot of values are going through the Observable I’m getting overlapping calls to my OnNext handler.
I could just add a lock to my OnNext delegate, but that doesn’t feel like the Rx way of doing things. What’s the best way to make sure I only have one call to my OnNext handler at a time, when I have multiple threads calling subject.OnNext(value);?
From Using Subjects on MSDN
So you should, as Brandon says in the comments, synchronize the subject and hand that out to your producer threads. e.g.