2016-11-12 1 views
0

질문 : 계속하기 전에 비동기 메서드의 입력을 어떻게 기다릴 수 있습니까?비동기 메서드의 비동기 메서드

일부 배경 정보 : QR 코드를 스캔 한 다음 스캔 한 값을 기준으로 데이터를로드하는 C# 응용 프로그램이 있습니다. 위 작업은 가능하지만 이제는 스캔 한 값이 올바른 카드인지 묻는 앱을 원합니다.

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);으로 전화를 시도했다. 이렇게하면 앱이 HandleScanResult()을 기다렸다가 if 문으로 진행해야합니다. 그러나, 이것은 다음과 같은 오류를 반환

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); 
}); 

t 전에 추가 async합니다.

그러나이 내용이 컴파일 된 것이므로 반드시 수행해야하는 것은 아닙니다. 과도하게 복잡하게 만들고있어 ContinueWith을 전혀 사용할 필요가 없습니다. async 메서드 본문에있는 경우 이미 사용중인 await 연산자를 사용하면 ContinueWith의 작업을보다 간단하게 수행 할 수 있습니다.

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

대단히 감사합니다. 나는 몇몇 예제 코드에서'ContinueWith'를 가지고 있었고, 왜 내가 그것을 사용 했는가? 다시 감사합니다, 만약 내가 더 많은 rep ;-)했다 +1 거라고 – Fons