2016-11-12 227 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