我正在使用ZXing.Net.Mobile库扫描QR码。我想将负责扫描的代码放在单独的类中,这样我就可以从中调用一个方法,它将返回结果。像这样的东西:
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();
if (result != null)
Console.WriteLine("Scanned Barcode: " + result.Text);
这是官方存储库中的一个示例,但它不起作用(至少对我而言)。 因此,我创建了一个类,并将DID工作形成的代码放在其他地方。这是课程代码:
public class QrHandler
{
public ZXingScannerPage scanPage { get; set; }
public string Result { get; set; }
public async Task<string> Scan()
{
var options = new ZXing.Mobile.MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat>
{
ZXing.BarcodeFormat.QR_CODE
},
TryHarder = false,
AutoRotate = false,
TryInverted = false,
};
scanPage = new ZXingScannerPage();
scanPage.AutoFocus();
scanPage.OnScanResult += (result) =>
{
scanPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
Application.Current.MainPage.Navigation.PopAsync();
try
{
Result = result.Text;
}
catch (Exception ex)
{
Result = ex.Message;
}
});
};
await Application.Current.MainPage.Navigation.PushAsync(scanPage);
return Result;
}
}
我从如下方法调用它:
public async Task<string> Validate()
{
string _Result = "OK";
QrHandler q = new QrHandler();
_Result = await q.Scan();
return _Result;
}
问题在于q.Scan()返回任何值之前Validate()返回_Result。在q.Scan()完成后不应该将其触发吗?
答案 0 :(得分:1)
在执行Scan()
事件处理程序之前,您无法从OnScanResult
返回。
尚不清楚何时引发此事件,但只要您希望在正常情况下引发此事件,就可以使用Scan()
在SemaphoreSlim
方法中异步阻止:
public async Task<string> Scan()
{
var options = new ZXing.Mobile.MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat>
{
ZXing.BarcodeFormat.QR_CODE
},
TryHarder = false,
AutoRotate = false,
TryInverted = false,
};
scanPage = new ZXingScannerPage();
scanPage.AutoFocus();
using (SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 1))
{
scanPage.OnScanResult += (result) =>
{
scanPage.IsScanning = false;
Device.InvokeOnMainThread(async () =>
{
await Application.Current.MainPage.Navigation.PopAsync();
try
{
Result = result.Text;
}
catch (Exception ex)
{
Result = ex.Message;
}
semaphore.Release();
});
};
await Application.Current.MainPage.Navigation.PushAsync(scanPage);
await semaphoreSlim.WaitAsync();
}
return Result;
}