我的问题:如何在继续之前等待来自异步方法的输入?异步方法中的异步方法
一些背景信息:我有一个C#应用程序扫描QR码,然后根据扫描的值加载数据。 上述工作,但现在我想让应用程序询问扫描的值是否是正确的卡片。
所施加的代码如下:
using ZXing.Mobile;
MobileBarcodeScanner scanner;
private bool Correct = false;
//Create a new instance of our scanner
scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.Dispatcher = this.Dispatcher;
await scanner.Scan().ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
if (Continue)
{
Continue = false;
Frame.Navigate(typeof(CharacterView));
}
HandleScanResult(Result)
被(脱脂向下):
async void HandleScanResult(ZXing.Result result)
{
int idScan = -1;
if (int.TryParse(result.Text, out idScan) && idScan != -1)
{
string ConfirmText = CardData.Names[idScan] + " was found, is this the card you wanted?";
MessageDialog ConfirmMessage = new MessageDialog(ConfirmText);
ConfirmMessage.Commands.Add(new UICommand("Yes") { Id = 0 });
ConfirmMessage.Commands.Add(new UICommand("No") { Id = 1 });
IUICommand action = await ConfirmMessage.ShowAsync();
if ((int) action.Id == 0)
Continue = true;
else
Continue = false;
}
}
问题是,Continue
保持假的时刻if (Continue)
在的第一块称为代码,因为消息框是异步的,应用程序在消息框完成之前继续到if语句。
我已经尝试给HandleScanResult()
一个任务返回类型并呼吁await HandleScanResult(t.Result);
。在进行if语句之前,这应该使应用程序等待HandleScanResult()
。 然而,这将返回以下错误:
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
因此,我对如何在继续之前等待输入的问题。
非常感谢!我有一些示例代码中的'ContinueWith',因此我使用了它。再次感谢你,如果我有更多的代表,我会+1 ;-) – Fons