Skip to content

Commit

Permalink
fix: sometimes the core dispatcher can't be fetched in constructor (#…
Browse files Browse the repository at this point in the history
…2255)

this fix is related to #2154 , some more testing showed that the former bugfix also has to be in place in ScheduleOnDispatcherNow
  • Loading branch information
jasonwurzel authored and glennawatson committed Nov 21, 2019
1 parent 11e7f70 commit d53a86b
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/ReactiveUI/Platforms/uap/SingleWindowDispatcherScheduler.cs
Expand Up @@ -43,17 +43,7 @@ public SingleWindowDispatcherScheduler()
return;
}

CoreDispatcher coreDispatcher;

try
{
coreDispatcher = CoreApplication.Views[0].Dispatcher;
}
catch
{
// in the XamlIsland case, accessing Views throws. Thus, falling back to the old way. This HAS to be initialized on the MainThread.
coreDispatcher = Window.Current.Dispatcher;
}
CoreDispatcher coreDispatcher = TryGetDispatcher();

Interlocked.CompareExchange(ref _dispatcher, coreDispatcher, null);
}
Expand Down Expand Up @@ -162,14 +152,32 @@ void RaiseToDispatcher(object sender, object e)
}
}

private CoreDispatcher TryGetDispatcher()
{
CoreDispatcher coreDispatcher;

try
{
coreDispatcher = CoreApplication.Views.FirstOrDefault()?.Dispatcher;
}
catch
{
// in the XamlIsland case, accessing Views throws. Thus, falling back to the old way. This HAS to be initialized on the MainThread.
coreDispatcher = Window.Current?.Dispatcher;
}

return coreDispatcher;
}

private IDisposable ScheduleOnDispatcherNow<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
try
{
// if _dispatcher is still null (and only then) CompareExchange it with the dispatcher from the first view found
if (_dispatcher == null)
{
Interlocked.CompareExchange(ref _dispatcher, CoreApplication.Views.FirstOrDefault()?.Dispatcher, null);
var dispatcher = TryGetDispatcher();
Interlocked.CompareExchange(ref _dispatcher, dispatcher, null);
}
}
catch
Expand Down

0 comments on commit d53a86b

Please sign in to comment.