以下是我编写的代码段。
Task.Factory.StartNew(() =>
{
BeginInvokeOnMainThread(() => scannerView.StartScanning(result =>
{
if (!ContinuousScanning)
{
Console.WriteLine("Stopping scan...");
scannerView.StopScanning();
}
var evt = this.OnScannedResult;
if (evt != null)
evt(result);
try
{
this.NavigationController.PushViewController(product, true);
}
catch(Exception e)
{
throw new Exception("Unable to push to the product page", e);
}
}, this.ScanningOptions));
});
但是当我尝试运行PushViewController时,我收到以下错误消息:
DECODE FAILED:System.Exception:尝试重定向到产品屏幕时发生错误---> System.Exception:无法推送到产品页面---> UIKit.UIKitThreadAccessException:UIKit一致性错误:您正在调用只能从UI线程调用的UIKit方法。
我如何从lambda中运行这样的东西?
答案 0 :(得分:1)
Task.Factory.StartNew(() => // <-- This starts a task which may or may not be on a
// separate thread. It is non-blocking, and as such, code
// after it is likely to execute before the task starts
{
BeginInvokeOnMainThread(() => scannerView.StartScanning(result =>
// This invokes a method on the main thread, which may or may not be the current thread
// Again, it's non-blocking, and it's very likely code after this will execute first
{
if (!ContinuousScanning)
{
Console.WriteLine("Stopping scan...");
scannerView.StopScanning();
}
var evt = this.OnScannedResult;
if (evt != null)
evt(result);
Console.WriteLine("Some output 1"); // <-- This output is executed once the entire
// task has been completed, which is I believe
// what you're looking for
}, this.ScanningOptions));
Console.WriteLine("Some output 2");
});
Console.WriteLine("lambda finished...");
答案 1 :(得分:0)
对于那些正在努力解决这个问题的人,我设法通过将我的代码包装在InvokeOnMainThread()中来实现它的工作
InvokeOnMainThread(() =>
{
this.NavigationController.PushViewController(product, true);
});