异步伺机而不是等待 [英] async await not waiting

查看:155
本文介绍了异步伺机而不是等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到类似的东西和阅读给出的所有答案,但couldn`t找到的东西,将它解释给我听。

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

下面是一个简单的code打开一个对话框弹出(WPF)。我想ShowOverlayView变成真后,该用户界面将是可访问的(这就是为什么异步的await)和程序等待,直到它完成,当用户点击关闭。

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".

小澄清:
ShowOverlayViewModel设置一个布尔真/假的ContentControl中的可见性属性。既然是这样的话那么我没有什么要等待的常规方式。

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".

目前,当被看得见的消息框立即显示该视图。
好像它不`吨等待的AutoResetEvent。

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

小更新:这似乎是相关具体到MessageBox。我试过的await code线后,Message属性改变,它只是are.Set后发生()。我还是很想知道为什么MessageBox的行为,因为它没有。

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;

    }

感谢您的帮助。

推荐答案

经典异步无效的bug。研究什么异步无效呢,为什么它是不好的做法。由于 ShowOptionsDialog()不返回等待被执行的任务立即继续。更改返回类型任务并等待方法调用的结果。

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.

您可以替换使用 TaskCompletionSource&LT事件;对象> 等待myTcs.Task 。一个TCS是一个比较TPL友好的事件。

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

这篇关于异步伺机而不是等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆