-
A pattern that comes up in my VS extensions is to use _ = Dispatcher.CurrentDispatcher.BeginInvoke(
() => {
// Work to be done later
}, null); The code is already known to be on the UI thread. It just uses Attempting to move my code to use // Option 1
_ = JoinableTaskFactory.RunAsync(
async () => {
await JoinableTaskFactory.SwitchToMainThreadAsync();
// work to be done later
});
// Option 2
_ = JoinableTaskFactory.RunAsync(
async () => {
await JoinableTaskFactory.SwitchToMainThreadAsync();
await Task.Delay();
// work to be done later
}); The case I worry about with Option 1 is whether everything could execute synchronously. Essentially if |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
There is an alwaysYield parameter you can pass to ensure the callback starts executing on the next UI loop iteration. |
Beta Was this translation helpful? Give feedback.
-
This is the closest equivalent: _ = JoinableTaskFactory.RunAsync(
async () => {
await Task.Yield();
// work to be done later
}); This requires the condition you met that you know you're already on the UI thread. It will use the default priority for that JTF instance to get back to the UI thread once you get off of it. If the callstack already has a JTF.Run on it, then the 'do later' work could get back on the UI thread because it will be seen as relevant to the overall JTF.Run delegate. If you don't want that, you'd have to mix If you're in code that can reference VS SDK assemblies, you can use StartOnIdle to easily ensure that the delegate will not execute till the main thread is back on the main message pump, and ready to process the priority you specify. |
Beta Was this translation helpful? Give feedback.
This is the closest equivalent:
This requires the condition you met that you know you're already on the UI thread. It will use the default priority for that JTF instance to get back to the UI thread once you get off of it.
If you didn't know you were on the main thread already, using
SwitchToMainThreadAsync(alwaysYield: true)
as @Therzok said is the best way to go since you want the delegate to run on the main thread.WithPriority
allocates a new object, so if you were to use that in high traffic code, you might want to use it once and store the result in a field for reuse.If th…