Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: sometimes the core dispatcher can't be fetched in constructor #2255

Merged
merged 1 commit into from
Nov 21, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions src/ReactiveUI/Platforms/uap/SingleWindowDispatcherScheduler.cs
Original file line number Diff line number Diff line change
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