await运算符只能在async方法中使用-但方法是异步的 [英] await operator can only be used within an async method - but method is asynchron

查看:1802
本文介绍了await运算符只能在async方法中使用-但方法是异步的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在VS12中使用MessageDialog.到目前为止,我已经使用过:

I want to use a MessageDialog in VS12. Until now I have used:

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;

现在,我想消除回调,并在等待中使用匿名方法.为了测试目的,我使用了:

Now I want to eliminate the callbacks and use an anonymous methode with await. For test purpose i used:

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'."

Problem is, await produces an error, even if ShowAsync() is obviously asynchron. "The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'."

这是什么问题?

好的,感谢您的评论,我现在要这样做:

Ok, thanks to your comments I now doing this:

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

现在可以了-非常感谢!

Now it works - thanks a lot!

推荐答案

但是从上面使用源代码的方法是构造函数(页面).

But the method which uses the source from above is a constructor (page).

您不能具有异步构造函数.将异步工作移出构造函数.也许将其移动到类似Load的事件中.我不知道您使用的是什么GUI框架,但它们始终有一个Load事件.

You cannot have asynchronous constructors. Move the async work out of the constructor. Maybe move it into a Load-like event. I don't know what GUI framework you're using but they always have a Load event.

这篇关于await运算符只能在async方法中使用-但方法是异步的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆