【发布时间】:2015-03-11 10:25:17
【问题描述】:
我想在 VS12 中使用 MessageDialog。到现在我都用过:
MessageDialog msgdlg = new MessageDialog("Choose a color", "How To Async #1");
msgdlg.DefaultCommandIndex = 1;
msgdlg.Commands.Add(new UICommand("Red", null, Colors.Red));
msgdlg.Commands.Add(new UICommand("Green", null, Colors.Green));
msgdlg.Commands.Add(new UICommand("Blue", null, Colors.Blue));
IAsyncOperation<IUICommand> asyncOp = msgdlg.ShowAsync();
asyncOp.Completed = OnMessageDialogShowAsyncCompleted;
现在我想消除回调并使用带有等待的匿名方法。出于测试目的,我使用了:
MessageDialog msgdlg = new MessageDialog("Choose a color", "#3");
msgdlg.Commands.Add(new UICommand("Red", null, Colors.Red));
msgdlg.Commands.Add(new UICommand("Green", null, Colors.Green));
msgdlg.Commands.Add(new UICommand("Blue", null, Colors.Blue));
// Show the MessageDialog
IAsyncOperation<IUICommand> asyncOp = msgdlg.ShowAsync();
IUICommand command = await asyncOp;
问题是,await 会产生错误,即使 ShowAsync() 显然是异步的。 “'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其返回类型更改为 'Task'。”
这里有什么问题?
好的,感谢你们的 cmets 我现在这样做了:
Loaded += async (sender, args) =>
{
#region Using await (from C# 5.0 on)
MessageDialog msgdlg = new MessageDialog("Choose a color", "#3");
msgdlg.Commands.Add(new UICommand("Red", null, Colors.Red));
msgdlg.Commands.Add(new UICommand("Green", null, Colors.Green));
msgdlg.Commands.Add(new UICommand("Blue", null, Colors.Blue));
// Show the MessageDialog
IAsyncOperation<IUICommand> asyncOp = msgdlg.ShowAsync();
IUICommand command = await asyncOp;
#endregion
};
现在可以使用了 - 非常感谢!
【问题讨论】:
-
请出示您的方法声明。大概它没有
async修饰符。为什么不呢? -
一旦你去异步,几乎你的整个调用堆栈也应该被标记为异步。一直异步。
-
“即使 ShowAsync() 显然是异步的” - 没关系。它在抱怨您当前正在编写的方法,而不是您正在调用的任何方法。
-
但是使用上面源代码的方法是构造函数(页面)。
标签: c# asynchronous async-await