The original address: devblogs.microsoft.com/oldnewthing…
The original author: devblogs.microsoft.com/oldnewthing…
Release date: April 8, 2020
We’ve been looking at a special case of non-agile delegates where a delegate is invoked on a background thread and you want to execute it synchronously on the UI thread. What about the other cases?
Yeah, what about them? Let’s write out a table.
Deal with at \ initiate at | A background thread | The UI thread |
---|---|---|
A background thread | There has been a | It makes no sense |
The UI thread | resume_synchronous | There has been a |
Other UI threads | resume_synchronous | resume_synchronous |
Two of the boxes are marked as having them. These are situations where the event is raised in the same apartment that you want to deal with, in which case everything is fine and there is no need to play the apartment switch game.
Two of the boxes are labeled RESUME_synchronous. In these cases, you want to run the handler synchronously on a UI thread that is not the one on which your handler is called. In these cases, you can use the resume_synchronous function we discussed last time. Of course, since you’re running on a UI thread, you shouldn’t block for a long time. This is especially true if you’re in the lower right corner, because when your event handler runs, you’re blackmailing two UI threads.
That leaves the last box, labeled “Makes no sense.”
This box is meaningless.
This box represents the case where the event is raised on a UI thread, but you want to process it synchronously on a background thread. Why do you do that?
The usual reason to move to background threads is so that you can perform long-running operations without slowing down the response time of the UI thread. But that doesn’t help us here, because the table is running code synchronously in another apartment, so the UI thread should remain unresponsive while the background thread works. Switching to background threads doesn’t work either. You might as well just do it on the UI thread.
Keep in mind that the entire discussion takes place in the context of running handlers simultaneously. If you can run the handler asynchronously, perhaps with the assistance of latency, then you should.
Next time we’ll finish this discussion by relating it to C++/WinRT in a different way.
Translation via www.DeepL.com/Translator (free version)