C# Lambda 无法完成执行

本文关键字:执行 Lambda | 更新日期: 2023-09-27 18:30:24

下面是我写的代码片段。

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 时,我收到以下错误消息:

解码失败:系统。异常:尝试重定向到产品屏幕时出错 --->系统。异常:无法推送到 UIKit --->产品页面。UIKit线程访问异常:UIKit 一致性错误:您正在调用只能从 UI 线程调用的 UIKit 方法。

我将如何从 lambda 中运行这样的东西?

C# 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...");

对于那些正在为此苦苦挣扎的人,我设法通过将我的代码包装在 InvokeOnMainThread() 中来让它工作

                    InvokeOnMainThread(() =>
                    {
                         this.NavigationController.PushViewController(product, true);
                    });