-2

How do i wait my method for a task to complete before the method returns.

public async void  barcodescanner()
{
    var scanner = new ZXing.Mobile.MobileBarcodeScanner();
    barcode =  await scanner.Scan();
}   

Definition of scaner.Scan():

public Task<Result> Scan();
Szabolcs Dézsi
  • 8,743
  • 21
  • 29
  • Thanks for the edit, but the code snippet insertion was not working properly. It looks it has changed. And I don't think i need a negative reputation for no fault of mine – LibinJoseph Feb 04 '16 at 01:28
  • What platform are you running this on? – Enigmativity Feb 04 '16 at 03:40
  • @Enigmativity : Xamarin.Android – LibinJoseph Feb 04 '16 at 03:51
  • Then you probably really shouldn't try to block this method. That's how mobile apps crash - the OS doesn't like apps that hang. – Enigmativity Feb 04 '16 at 04:06
  • True. But that call is suppose to load a barcode scanner, the result need to be obtained before i continoue – LibinJoseph Feb 04 '16 at 04:11
  • But that's what `async`/`await` does for you. It makes the code appear to wait for the result, but the UI remains responsive. You then need to change the `void` to `Task` to be able to await this code when you call it. Just as Alexei says in his answer. – Enigmativity Feb 04 '16 at 04:40

2 Answers2

1

You can't wait for result of async void method - it is explicitly "fire and forget" behavior.

If you want to wait for completion - return Task and .Wait on it

public async Task  barcodescanner() {...}

barcodescanner().Wait(); 

Notes:

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

You could always do this:

public void barcodescanner()
{
    var scanner = new ZXing.Mobile.MobileBarcodeScanner();
    barcode =  scanner.Scan().Result;
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172