Does it makes sense to store/cache the TaskScheduler returned from TaskScheduler.FromCurrentSynchronizationContext while loading a WPF app and use it every from there on? Are there any drawbacks of this kind of usage?
What I mean from caching is to store a reference to the TaskScheduler in a singleton and make it available to all parts of my app, probably with the help of a DI/IoC container or worst case in a bare ol’ singleton.
As Drew says, there’s no performance benefit to doing this. But there might be other reasons to hold onto a
TaskScheduler.One reason you might want to do it is that by the time you need a
TaskSchedulerit may be too late to callFromCurrentSynchronizationContextbecause you may no longer be able to be certain that you are in the right context. (E.g., perhaps you can guarantee that your constructor runs in the right context, but you have no guarantees about when any of the other methods of your class are called.)Since the only way to obtain a
TaskSchedulerfor aSynchronizationContextis through theFromCurrentSynchronizationContextmethod, you would need to store a reference to theTaskScheduleritself, rather than just grabbingSynchronizationContext.Currentduring your constructor. But I’d probably avoid calling this “caching” because that word implies that you’re doing it for performance reasons, when in fact you’d be doing it out of necessity.Another possibility is that you might have code that has no business knowing which particular
TaskSchedulerit is using, but which still needs to use a scheduler because it fires off new tasks. (If you start new tasks, you’re choosing a scheduler even if you don’t realise it. If you don’t explicitly choose which scheduler to use, you’ll use the default one, which isn’t always the right thing to do.) I’ve written code where this is the case: I’ve written methods that accept aTaskSchedulerobject as an argument and will use that. So this is another scenario where you might want to keep hold of a refernce to a scheduler. (I was using it because I wanted certain IO operations to happen on a particular thread, so I was using a custom scheduler.)Having said all that, an application-wide singleton doesn’t sound like a great idea to me, because it tends to make testing harder. And it also implies that the code grabbing that shared scheduler is making assumptions about which scheduler it should be using, and that might be a code smell.