Is there a situation where a SynchronisationContext is used over multiple threads/tasks in Blazor?
I want to determine whether a method has an components BuildRenderTree in its call stack. To do so i created a custom ComponentBase where i wrap the BuildRenderTree with custom code. My approach would be to check the SynchronisationContext. As i understood it is uniquely for one component, and therefor the execution of BuildRenderTree will not be "interrupted" by other threads/tasks with the same SynchronisationContext set. Did i get this right? Are there any pitfalls with using the SynchronisationContext for this case? (i am not sure if the components used in the razor file are rendered within the BuildRenderTree but i would handle this case correctly alreay)
2
Answers
Not really. It is attached to the SignalR circuit and shared by the whole UI. It is null when running on WebAssembly.
BuildRenderTree() is not async, it won’t be interrupted by other Tasks. It might be pre-empted by other threads but that should not affect what’s on the call stack.
To quote the Microsoft Documentation:
However, this won’t help you. No event triggered by a user action or method you call will have
BuildRenderTree
in it’s call stack. Events and user defined methods queueRenderFragment
s on the Renderer’s Render queue by callingStateHasChanged
.Here’s the code:
The Renderer services the queue and posts
RenderFragment
s placed on the queue to the Synchronisation Context.Here’s the RenderFragment containing the call to
BuildRenderTree
– defined in theComponentBase
constructor: