我创建了一个名为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
运算符。为什么会这样?
我还需要问其他问题:
Instance
方法吗?怎么样?Task<bool>
更新
基于对这个伟大社区的有用答案和评论,我已经编辑了这个方法(现在是一个属性):
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()
答案 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;
}
}