Redth / ZXing.Net.Maui

Barcode Scanning for MAUI?
MIT License
461 stars 151 forks source link

App using control and .NET 8 RC2 crashes on Android upon detecting a QR code #140

Open gartaud opened 11 months ago

gartaud commented 11 months ago

Hello

I tried the control for a proof-of-concept app using VS 2022 preview 5.

Everything seems fine until the control detects a QR code. Then the control crashes and brings the app down before the user event handler is called.

Is that expected? Thanks.

gartaud commented 11 months ago

After debugging further, it turns out that the issue is that the callback upon detecting a barcode is made from a worker thread that is different from the thread that registered the callback.

While this makes sense, it would be good to explain in the documentation that the callback is made from a different thread.

CarlosAdrianM commented 11 months ago

I have the same error even if I ensure that the operation is made in the main thread:

protected void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
        barcodeView.IsDetecting = false;
        ViewModel.HandleBarcodeDetected(e);
    });
}

How did you solved it?

gartaud commented 11 months ago
        protected void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
        {
            var first = e.Results?.FirstOrDefault();
            if (first is not null)
            {
                Dispatcher.Dispatch(() =>
                {
                    // Update BarcodeGeneratorView
                    barcodeGenerator.ClearValue(BarcodeGeneratorView.ValueProperty);
                    barcodeGenerator.Format = first.Format;
                    barcodeGenerator.Value = first.Value;

                    // Update Label
                    ResultLabel.Text = $"Barcodes: {first.Format} -> {first.Value}";
                });
            }
        }

As in https://github.com/Redth/ZXing.Net.Maui/blob/main/BigIslandBarcode/MainPage.xaml.cs

gartaud commented 11 months ago

See also https://github.com/dotnet/maui/discussions/7518