async await not waiting

让人想犯罪 __ 提交于 2019-12-02 10:49:52

问题


Tried to find something similar and read all the answers given but couldn`t find something that will explain it to me.

Here is a sample code for opening a dialog popup (WPF). I want after the ShowOverlayView turns to True, that the UI will be accessible (this is why the async-await) and the program to wait until it is finished when the user clicks "Close".

Small clarification: ShowOverlayViewModel sets a boolean to true/false for the Visibility property of a ContentControl. Since this is the case then I have nothing to wait for "the regular way".

Currently when the view is being "visible" the MessageBox is immediately shown. Seems like it doesn`t wait for the AutoResetEvent.

Small update: It seems to be relevant specific to the MessageBox. I tried to change the Message property after the await code line and it occurred only after the are.Set(). I would still love to know why did the MessageBox act as it did.

    private void CommandAction()
    {
        ShowOptionsDialog();
        MessageBox.Show("");
    }

    private async void ShowOptionsDialog()
    {
        var are = new AutoResetEvent(false);

        var viewmodel = new DialogPopupViewModel();
        viewmodel.Intialize("some title", "some message", DialogPopupViewModel.YesNoCancelButtons);
        SetOverlayViewModel(viewmodel);

        viewmodel.SetCloseViewAction(() =>
            {
                HideOverlayView();
                are.Set();
            });
        ShowOverlayView = true;

        await Task.Factory.StartNew(() =>
            {
                are.WaitOne();
                //return viewmodel.DialogResult;
            });
        //return DialogResultEnum.Cancel;

    }

Thanks for the help


回答1:


Classic async-void bug. Research what async void does and why it's bad practice. Since ShowOptionsDialog() does not return a task that is awaited execution continues immediately. Change the return type to Task and await the result of the method call.

You can replace the event with a TaskCompletionSource<object> and say await myTcs.Task. A TCS is a more TPL-friendly event.



来源:https://stackoverflow.com/questions/36115580/async-await-not-waiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!