ExcelAsyncUtil.QueueAsMacro async support

373 views
Skip to first unread message

paba...@gmail.com

unread,
Feb 15, 2021, 11:10:57 AM2/15/21
to Excel-DNA
hi Govert, checking the group and I dont see anything answering this question specifically.

I have code called from a button where we have a mix of async network related and Excel related actions. This is currently being supported by ExcelAsyncUtil.QueueAsMacro(async () => { }); style code where any network related activities can be awaited and the Excel thread will be freed up to perform other activities when required.

There is no synchronization context available at this time and so I believe it is possible for the await to continue on a threadpool thread? If so this would mean any calls to the C API made in the QueueAsMacro method might fail?
If this is the case is there a pattern you would suggest to run async code and continue on the Excel thread?

Govert van Drimmelen

unread,
Feb 22, 2021, 9:44:04 AM2/22/21
to Excel-DNA
You'll need to experiment a bit with the initial QueueAsMacro call,  but one option for ensuring that async/await continuations happen on the main Excel thread in a macro context (like the context where the ExcelAsyncUtil.QueueAsMacro runs) is to pass an ExcelSynchronizationContext to Task.Run, and the use the resulting task.

Here is a pattern you can try:

One problem is that some of the async calls might not have to run on the Excel main thread, while the ones that talk back to Excel should.
For that case, you might need to split the methods, and the have some .ConfigureAwaits strategically placed

A more explicit alternative is to wrap the parts that interact with Excel in their own ExcelAsyncUtil.QueueAsMacro calls. That is safe to call from any thread and will at least queue the calls in the right sequence. You just have to be a bit careful if you want to wait for that work to return before doing something else.

Overall it's a tricky story and depends on the complexity you have, and how much code you need with this pattern.

Write back or let me know if you need some more help working it out.

Cheers,
Govert
Reply all
Reply to author
Forward
0 new messages