2017-12-26 4 views
-1

私はC#Xamarinプロジェクトで作業しています。このプロジェクトでは、QRコードスキャナーを実装するためにZXing.Net.Mobileクラスライブラリを使用しました。スキャン完了後のXamarin ZXingスキャナ書き込みロジック

ユーザーがQRコードをスキャンすると、URLが表示されます。これは、Webサービスにデータを送信するために使用されます。私の問題は次のとおりです。メソッドの実行中途中connectToBackendスレッドBeginInvokeOnMainThreadの有効期限が切れています。結果として、の実行はconnectToBackendを終了しません。このスレッドシナリオをどのように処理してサーバー要求を処理できるかについては、私は助けが必要です。

public void ShowScannerPage() { 

     ZXingScannerPage scanPage = new ZXingScannerPage(); 

     scanPage.OnScanResult += (result) => { 

      // stop scanning 
      scanPage.IsScanning = false; 

      ZXing.BarcodeFormat barcodeFormat = result.BarcodeFormat; 
      string type = barcodeFormat.ToString(); 


    // This thread finishes before the method, connectToBackend, inside has time to finish 
      Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { 

       //_pageService.PopAsync(); 
       _pageService.PopAsync(); 


       App.UserDialogManager.ShowAlertDialog("The Barcode type is : " + type, "The text is : " + result.Text, " OK"); 

     // problem here 
       connectToBackend(result.Text); 
      }); 

    // If I put connectToBackend here there is still a problem 

     }; 

     _pageService.PushAsync(scanPage); 

    } 

詳細については、私はMVVMのアプローチを使用しています。ページがあり、ユーザーがスキャンボタンをクリックすると、ShowScannerPageメソッドは、ZXing.Netモバイルライブラリを使用してモバイル上のスキャナビューを開きます。私は下のクラスをペーストした。

public class WorkoutViewModel { 

    public ICommand ScanCommand { get; private set; } 

    public readonly IPageService _pageService; 

    public WorkoutViewModel(IPageService pageService) { 

     this._pageService = pageService; 

     ScanCommand = new Command(ShowScannerPage); 

    } 

    public void ShowScannerPage() { 

     ZXingScannerPage scanPage = new ZXingScannerPage(); 

     scanPage.OnScanResult += (result) => { 

      // stop scanning 
      scanPage.IsScanning = false; 

      ZXing.BarcodeFormat barcodeFormat = result.BarcodeFormat; 
      string type = barcodeFormat.ToString(); 


    // This thread finishes before the method, connectToBackend, inside has time to finish 
      Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { 

       //_pageService.PopAsync(); 
       _pageService.PopAsync(); 


       App.UserDialogManager.ShowAlertDialog("The Barcode type is : " + type, "The text is : " + result.Text, " OK"); 

     // problem here 
       connectToBackend(result.Text); 
      }); 

    // If I put connectToBackend here there is still a problem 

     }; 

     _pageService.PushAsync(scanPage); 

    } 

    public async void connectToBackend(String nodes) { 

     // call api ... 

    } 

}

答えて

0

あなたはawaitキーワードを指定せずに非同期機能(async void connectToBackend(String nodes))を呼んでいます。

async」というイベントをscanPage.OnScanResult += (result) => {と定義して、asyncconnectToBackend機能を定義できると思います。

だと思います。BeginInvokeOnMainThreadは不要です

関連する問題