I want to update the position of certain UI elements in my WPF application in a loop. After each iteration, the UI should be rerendered to make the changes visible. The updating process can stopped at any point using a CancellationToken. Since the cancellation is performed by the user, the UI must remain responsive to input. I wrote the following method to do this:
public async Task DoStuff(CancellationToken token)
{
do
{
DoLayoutUpdate();
await Dispatcher.Yield(DispatcherPriority.Input);
} while (!token.IsCancellationRequested);
}
This mostly works: The UI is rerendered after each iteration and I can click the button to cancel the operation so input works as well. The problem is: if there is no input and nothing to rerender, the method gets stuck in the Yield. Presumably the thread is blocked waiting for input or render tasks.
If I increase the DispatcherPriority
to Render
, the method does not get stuck anymore but then the UI isn't updated and input isn't handled anymore.
How can I fix this?