i have basic class showing notifications fades in (and out) asynchronous delays in attempt keep ui responsive.
public partial class notification : form { public notification(string message) { initializecomponent(); txtnotification.text = message; } async new public void show() { fadein(); await task.delay(7000); fadeout(); } async void fadein() { opacity = 0; base.show(); while (opacity < 1.0) { await task.delay(50); opacity += 0.05; } opacity = 1; } async void fadeout() { while (opacity > 0.0) { await task.delay(50); opacity -= 0.05; } opacity = 0; hide(); } } i have ui event handler wants perform heavy lifting, show notification.
async public void myhandler(args) { await task.run(() => { system.diagnostics.debug.writeline("do something!"); }); new notification("work completed!").show(); } and running deadlock during notification fadein 'await task.delay(50)'. i'm new async await malarkey understand can't configureawait because need fade notification in on ui thread , using async , await 'all way down' were. if remove line in event handler work there no deadlock, i'm awaiting complete can't understand why i'm ending in deadlock. surely i've misunderstood here?
as requested i've removed async void's , reduced code:
public partial class notification : form { public notification() { initializecomponent(); } async task fadein() { opacity = 0; base.show(); while (opacity < 1.0) { await task.delay(50); opacity += 0.05; } } } and i've discovered issue not reproduce in winform app, reproduce described in outlook addin. increased simplicity i'm using addin startup event , following code shows notification no problem
async private void thisaddin_startup(object sender, system.eventargs e) { await new notification().fadein(); } but code causes hang/deadlock described previously
async private void thisaddin_startup(object sender, system.eventargs e) { await task.run(() => { system.diagnostics.debug.writeline("do something!"); }); await new notification().fadein(); } i've created new addin, there no other code, figure problem must outlook.(?)
@stephencleary provided solution. add following line before offending code.
synchronizationcontext.setsynchronizationcontext(new windowsformssynchronizationcontext());
Comments
Post a Comment