异步方法中的异步方法

时间:2016-11-12 22:33:12

标签: c# visual-studio asynchronous

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

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

答案 0 :(得分:1)

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

至于错误消息,它告诉您可以解决编译器错误,如下所示:

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

请注意async之前的额外t

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

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