我的問題:如何在繼續之前等待來自異步方法的輸入?異步方法中的異步方法
一些背景信息:我有一個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