以下是我编写的代码段。
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时,出现以下错误消息:
解码失败:System.Exception:尝试重定向到产品屏幕时发生错误---> System.Exception:无法推送到产品页面---> UIKit.UIKitThreadAccessException:UIKit一致性错误:您正在调用UIKit只能从UI线程调用的方法。
我将如何在lambda中运行类似的内容?
最佳答案
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...");
关于c# - C#Lambda不会完成执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34803655/