Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

UWP Dispatcher should use the internal core dispatcher for state #15716

Merged
merged 2 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,13 @@ protected override void Init()
var threadpoolButton = new Button { Text = "Update Instructions from Thread Pool" };
layout.Children.Add(threadpoolButton);

this.Dispatcher.BeginInvokeOnMainThread(() => { instructions.Text = "updated from thread pool 1"; });
this.Dispatcher.BeginInvokeOnMainThread(() => { instructions.Text = "updated from thread pool 1 IsInvokeRequired=" + this.Dispatcher.IsInvokeRequired; });

threadpoolButton.Clicked += (o, a) =>
{
Task.Run(() =>
{
this.Dispatcher.BeginInvokeOnMainThread(() => { instructions.Text = "updated from thread pool 2"; });
this.Dispatcher.BeginInvokeOnMainThread(() => { instructions.Text = "updated from thread pool 2 IsInvokeRequired=" + this.Dispatcher.IsInvokeRequired; });
});
};

Expand Down
2 changes: 1 addition & 1 deletion Xamarin.Forms.Platform.UAP/Dispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ public Dispatcher(CoreDispatcher coreDispatcher)
_coreDispatcher = coreDispatcher;
}

bool IDispatcher.IsInvokeRequired => Device.IsInvokeRequired;
bool IDispatcher.IsInvokeRequired => !_coreDispatcher.HasThreadAccess;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the main fix to use the correct core dispatcher. The Device.IsInvokeRequired implementation only verifies against the main/first dispatcher.

}
}
5 changes: 5 additions & 0 deletions Xamarin.Forms.Platform.UAP/DispatcherProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public IDispatcher GetDispatcher(object context)
s_current = new Dispatcher(renderer.ContainerElement.Dispatcher);
return s_current;
}
else
{
s_current = new Dispatcher();
return s_current;
}
Comment on lines +30 to +34
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to fix the scenario where you try and get the dispatcher before the renderer is created, so we fall back to the window's dispatcher. This is because the dispatcher is cached and if there is no renderer, the FallbackDispatcher is used - and that is always using the first/main thread via the Device.

}

return null;
Expand Down