C# Lambda 无法完成执行

标签 c# ios lambda zxing

下面是我写的代码片段。

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 一致性错误:你是调用只能从 UI 线程调用的 UIKit 方法。

我将如何从 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# Lambda 无法完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803655/

相关文章:

c# - 我们如何在最新的 mongodb c# 驱动程序中使用 CreateIndexModel 创建多个索引

c# - iTextSharp 一切正常,但在打开 pdf 文档时出现奇怪的错误

c# - PowerShell - 如何在运行空间中导入模块

c# - 为 WebForms 网站项目添加 MVC 支持

c# - 对 Func<> 谓词表达式的困惑

iphone - 以编程方式创建两个 UIPickerViews 但所有值都排在第二位

ios - 防止点击覆盖时取消选择注释

ios - UITableViewCell 当单元格可见时重新添加自定义内容

java - "Lambdifying"Java中的scala函数

在声明点按值捕获 C++11 lambda 捕获