Reputation: 3416
I'm new to RX and starting to understand a few concepts.. that one I didn't find on the web.
I'm using a timer in my code:
Observable.Timer(TimeSpan.FromSeconds(2), schedulerProvider.CurrentThread);
// where schedulerProvider.CurrentThread is actually Scheduler.CurrentThread
I understand that Timer is a Cold Observable, and every subscriber will get its private timer that will run for 2 seconds from when it subscribed.
I'm creating that cold observable in thread1
and subscribing to it with thread2
[,thread3
, thread4
etc...]
So the question is: in which thread will it run?
Please provide a source.
Thank you!
EDIT: Thanks for the detailed answer. Now I know that my question has an issue.The scheduler that passed as second parameter is NOT for subscribers scheduling, but for running the Timer. Most of RX operators runs on the same thread by default, but Timer is one (of several) exceptional. By default, the timer itself will run on the Thread Pool, and call OnNext on its same thread. If you ask it to use CurrentThread scheduler, the timer itself will run on the same thread (like most of Rx operators) and subscribers will be called on the same thread. (this is not very recommended though for regular use cases).
Upvotes: 2
Views: 497
Reputation: 117027
Why not do run some tests to find out?
Here's what I did:
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Observable
.Timer(TimeSpan.FromSeconds(2.0), Scheduler.CurrentThread)
.Subscribe(x => Console.WriteLine(Thread.CurrentThread.ManagedThreadId));
The produced:
12 12
Then I tried this:
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Observable
.Timer(TimeSpan.FromSeconds(2.0))
.Subscribe(x => Console.WriteLine(Thread.CurrentThread.ManagedThreadId));
That produced:
12 13
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Observable
.Timer(TimeSpan.FromSeconds(2.0))
.ObserveOn(Scheduler.CurrentThread)
.Subscribe(x => Console.WriteLine(Thread.CurrentThread.ManagedThreadId));
That produced:
11 27
All of this boils down to Scheduler.CurrentThread
capturing the current thread context at the time that the Scheduler.CurrentThread
parameter is evaluated.
In the first block of code it was captured at the time that the timer was created - in other words, my console thread.
In the final block it was captured after the timer fired so it captured the thread that the timer fired on.
Upvotes: 5