在关闭方法中不能使用async

时间:2018-02-27 15:58:58

标签: c# wpf

我创建了一个名为Instance的方法,允许我拥有Settings窗口的单个实例,如下所示:

    public static async Task<Settings> Instance()
    {
        if (AppWindow == null)
        {
            AppWindow = new Settings();

            AppWindow.Closing += async (x, y) =>
            {
                bool close = await AppWindow.CheckSettings();
                y.cancel = (close) ? true : false;
                AppWindow = null;
            };
        }

        return AppWindow;
    }

CheckSettings具有以下结构:

private async Task<bool> CheckSettings()
{   
     //just as example
    return true;
}

方法Instance()告诉我里面没有await运算符。为什么会这样?

我还需要问其他问题:

  1. 这个逻辑可以在属性中使用而不是Instance方法吗?怎么样?
  2. 可以在不实施Task<bool>
  3. 的情况下关闭窗口

    更新

    基于对这个伟大社区的有用答案和评论,我已经编辑了这个方法(现在是一个属性):

        public static Settings Instance
        {
            get
            {
                if (AppWindow == null)
                {
                    AppWindow = new Settings();
    
                    AppWindow.Closing += async (x, y) =>
                    {
                        bool close = await AppWindow.CheckSettings();
                        y.Cancel = close;
    
                        //AppWindow.Close();
                        //AppWindow = null;
                    };
                }
    
                return AppWindow;
            }
        }
    

    问题是Cancel没有等待CheckSettings()

1 个答案:

答案 0 :(得分:1)

在致电Cancel方法之前,将true媒体资源设为async

public static Settings Instance
{
    get
    {
        if (AppWindow == null)
        {
            AppWindow = new Settings();
            //attach the event handler
            AppWindow.Closing += AppWindow_Closing;
        }
        return AppWindow;
    }
}

private static async void AppWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;

    //call the async method
    bool close = await AppWindow.CheckSettings();
    if (close)
    {
        AppWindow win = (AppWindow)sender;
        //detach the event handler
        AppWindow.Closing -= AppWindow_Closing;
        //...and close the window immediately
        win.Close();
        AppWindow = null;
    }
}