c# - Waiting for all the threads spawned by async method while unit Testing -
i unit testing viewmodel in wpf application , there delegate command calls method further calls async method inside . have wait every task finished before calling assert statement. method called delegate command :
private void methodcalled() { this.uiservice.setbusystate(); uiexecutehelper executehelper = new uiexecutehelper(viewname.window); executehelper.executeasync(() => { // stuff method1(); } } now waiting method in following way in unit test:
try { var task = task.factory.startnew(() => { classobj.delegatecommand.execute(); }); var aftertask = task.continuewith((myobject)=> { classobj.load(); assert.areequal(true, someflag); }, taskcontinuationoptions.onlyonrantocompletion); } but still not waiting inner tasks spawned finished. please suggest
there delegate command calls method further calls async method inside it.
@jimwooley correctly identified root of problem. 1 of reasons avoid async void because async void methods not (easily) testable.
the best solution suggested:
- factor actual logic of command separate,
task-returning method. - within delegate command,
awaitmethod. - your unit tests can call
async taskmethod rather invoking delegate command.
however, if insist on doing hard way, you'll need install custom synchronizationcontext , track number of asynchronous operations. or can use asynccontext type you:
await asynccontext.run(() => classobj.delegatecommand.execute()); classobj.load(); assert.areequal(true, someflag);
Comments
Post a Comment