c# - Incorrect async/await working, Excel events in Excel Application Level Add-in -
i faced problem using async /await in add-in application, have custom task pane , user can download data it, there problems:
after awaited operation completed control not returned previous execution context. created example windows forms , paste same method awaiting , works fine - can use form controls after await operation, not in add-in, have call custom task pane invoke method. simple example:
private void searchpanebutton_click(object sender, eventargs e) { search(); } private async void search() { var searchtext = searchtextbox.text; searchpanebutton.text = "loading…"; var data = await new dataserviceclient().getdataasync(searchtext); this.invoke((methodinvoker)(() => { searchpanebutton.text = "search"; toggleworkbookevents(); })); }
in add-in need handle events - worksheet changed, worksheet activated/deactivated, these events disappear , isn't fired after await operation , have use "toggling"(remove+add) events after each await using. simple example:
private void toggleworkbookevents() { var excel = globals.bpnaddin.application; //need ensure event not set twice excel.sheetactivate -= checksheetfordata; excel.sheetactivate += checksheetfordata; if (excel.activeworkbook != null) { var activesheet = globals.bpnaddin.getactiveworksheet(); //need ensure event not set twice activesheet.change -= worksheet_changed; activesheet.change += worksheet_changed; } }
so maybe vsto framework can not support new features(like async await) of last versions .net framework?
this long-standing issue office plugins: don't provide synchronizationcontext
.
as mention on blog, can work around ensuring have proper synchronizationcontext
. bit hacky, works:
private async void searchpanebutton_click(object sender, eventargs e) { if (synchronizationcontext.current == null) synchronizationcontext.setsynchronizationcontext(new windowsformssynchronizationcontext()); await searchasync(); } private async task searchasync() { var searchtext = searchtextbox.text; searchpanebutton.text = "loading…"; var data = await new dataserviceclient().getdataasync(searchtext); searchpanebutton.text = "search"; toggleworkbookevents(); }
as far "toggling events" problem goes, have no idea.
Comments
Post a Comment