![](/img/trans.png)
[英]The 'await' operator can only be used within an async > method
[英]await operator can only be used within an async method - but method is asynchron
我想在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;
問題是,即使ShowAsync()顯然是異步的,await也會產生錯誤。 “'await'運算符只能在異步方法中使用。請考慮使用'async'修飾符標記該方法,並將其返回類型更改為'Task'。”
這里有什么問題?
好的,感謝您的評論,我現在這樣做:
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
};
現在可以正常工作-非常感謝!
但是,從上方使用源代碼的方法是構造函數(頁面)。
您不能具有異步構造函數。 將異步工作移出構造函數。 也許將其移動到類似Load
的事件中。 我不知道您使用的是什么GUI框架,但它們始終有Load
事件。
您應該使方法async
。不能在non-async
函數內部使用await
。
調用這些代碼的函數也應該是異步的。 請在下面的MS官方樣本中查看詳細信息。 注意,ForgotPassword的返回是異步Task <ActionResult>而不是ActionResult。
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account",
new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password",
"Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.