2016-11-12 242 views
0

我的问题:如何在继续之前等待来自异步方法的输入?异步方法中的异步方法

一些背景信息:我有一个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. 

因此,我对如何在继续之前等待输入的问题。

回答

1

您不能等到async void方法完成。 Task是返回类型,它允许呼叫者获得某种指示操作已完成的信号。你做了正确的事情改变该方法async Task

至于错误信息,它告诉你,你可以摆脱编译器错误如下:

await scanner.Scan().ContinueWith(async t => 
{ 
    if (t.Result != null) 
     await HandleScanResult(t.Result); 
}); 

注意额外asynct之前。

但是,仅仅因为这个编译,并不意味着这是你应该做的。你让事情变得过于复杂,你根本不需要使用ContinueWith。当您在async方法正文中时,您已经使用的await运算符可以执行ContinueWith会执行的操作,但以更直接的方式执行。

var scanResult = await scanner.Scan(); 
if (scanResult != null) 
    await HandleScanResult(scanResult); 
+0

非常感谢!我有一些示例代码中的'ContinueWith',因此我使用了它。再次感谢你,如果我有更多的代表,我会+1 ;-) – Fons