我正在开发一个C#Xamarin项目。在项目中,我使用了ZXing.Net.Mobile类库来实现QR代码扫描程序。
用户扫描QR码后,会显示一个网址。用于将数据发送到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 Mobile库在其移动设备上打开扫描仪视图。我在下面粘贴了我的课程。
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 :(得分:0)
您正在调用不带async void connectToBackend(String nodes)
关键字的异步函数(await
)。
我认为您可以定义“async
”事件scanPage.OnScanResult += (result) => {
,以便您async
connectToBackend
功能。
我认为BeginInvokeOnMainThread
不是必需的