我正在从事C#Xamarin项目。在项目中,我使用了zxing.net.mobile类库来实现QR码扫描仪。
用户扫描QR码后,显示了一个URL。用于将数据发送到Web服务。我的问题是:在执行方法 connectTobackend 的中途中间。结果,执行 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方法。我有一个页面,当用户单击"扫描"按钮时,方法显示CannerPage使用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 ...
}
}
您在没有await
关键字的情况下调用异步函数(async void connectToBackend(String nodes)
)。
我认为您可以定义" async
"事件scanPage.OnScanResult += (result) => {
,因此您可以async
connectToBackend
函数。
我认为BeginInvokeOnMainThread
不是必需的