【问题标题】:Cannot use async in closing method不能在关闭方法中使用异步
【发布时间】:2018-02-28 00:31:49
【问题描述】:

我创建了一个名为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&lt;bool&gt; 的情况下关闭窗口

更新

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

    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()

【问题讨论】:

  • 你没有任何事情async那为什么要异步呢?
  • @nvoigt 我需要异步,因为在 CheckSettings 中我有一些 Mahapp 框架的方法,例如 await ShowMessageAsync()
  • Instance() 方法内部没有异步调用,此外,afaik 异步 EventHandler 对 CancelEventHandler 是不可行的,因为事件将在您的 Handler 完成之前被调用并继续,因此设置 Cancel属性不会做太多。
  • @nvoigt 检查更新

标签: c# wpf


【解决方案1】:

在调用async 方法之前,将Cancel 属性设置为true

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;
    }
}

【讨论】:

  • OP 在调用该方法之前不知道是否要取消关闭。该方法的重点是确定他们是否应该取消关闭表单。您现在无法关闭此表单。
  • 是吗?仅当 CheckSettings 返回 true 时,窗口才会关闭。你的意思是什么?
  • 然后又会被取消,表单永远不会关闭。
  • 没有。因为一旦 CheckSettings 方法返回 true,事件处理程序就会被分离。然后按预期关闭“表单”。
  • 在投反对票之前,您应该尝试一下代码(或者至少仔细阅读一下)。
猜你喜欢
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多