Reputation: 25631
I need an STA thread to use with Observable.Create
, (the scheduler is defined using the SubScribeOn
method). My question is what is the best way to create an STA thread in Rx.
Currently I have the following working with the NewThreadScheduler but I could use the EventLoopScheduler instead.
Which is better suited for creating an STA thread?
Func<ThreadStart, Thread> func = x =>
{
var thread = new Thread(x) { IsBackground = true };
thread.SetApartmentState(ApartmentState.STA);
return thread;
};
return new NewThreadScheduler(func);
.Net version: 4.0 (WPF)
Rx version: 2.0.21103.1
Upvotes: 2
Views: 564
Reputation: 29776
They achieve different goals:
NewThreadScheduler
will dispatch events to subscribers as soon as possible by using multiple threads (concurrency). Threads will be reused for efficiency. Pick this because you want subscribers to get their events asap without other subscribers holding things up.
EventLoopScheduler
will dispatch events to subscribers on the same thread. Pick this one because you want everything run on the one thread.
Upvotes: 3
Reputation: 2652
EventLoopScheduler
and NewThreadScheduler
are both acceptable, depending upon your needs. The difference is essentially this:
EventLoopScheduler
employs single-threaded asynchrony; i.e., a dedicated background thread. If you create an instance of this scheduler and pass it around to many operators, then all actions scheduled by those operators (including, but not limited to, calls to OnNext
) are enqueued and serialized onto a single thread.NewThreadScheduler
employs concurrency. As an optimization, overlapping notifications will appear on the same thread, though you should not rely on this.Upvotes: 4