【问题标题】:UWP "The name dispatcher does not exist in the current context"UWP“当前上下文中不存在名称调度程序”
【发布时间】:2019-05-06 05:29:23
【问题描述】:

在 UWP C# 应用程序中,需要后台(即工作)线程来使用 UI 线程来显示图像。但是不知道怎么编译Dispatcher.RunAsync()

using Foundation;
using System;
using UIKit;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
using System.Windows.Threading;                 <<<<<<<<<<  gets error
using Windows.UI.Core;                          <<<<<<<<<<  gets error

public async static void process_frame()
{

    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        // "the name dispatcher does not exist in current context"
        //UI code here:
        display_frame();
    });
}


public void display_frame()
{
    var data = NSData.FromArray(System_Hub_Socket.packet_frame_state.buffer);

    UIImageView_camera_frame.Image = UIImage.LoadFromData(data);
}

最新方法

public async static void process_frame( /* ax obsolete: byte[] camera_frame_buffer, int frame_size_bytes */  )
{
    await Task.Run( () => { viewcontroller.display_frame(); } );
}


// [3]
// Copies latest frame from camera to UIImageView on iPad.
// UI THREAD

public Task display_frame()
{
  var data = NSData.FromArray ( System_Hub_Socket.packet_frame_state.buffer);        
  <<<<<< ERROR 

  UIImageView_camera_frame.Image = UIImage.LoadFromData( data );

  return null;
}

最新方法出错

【问题讨论】:

  • display_frame 应该是 public Task display_frame() 如果你希望它像 void,如果你需要返回一些东西,它应该是 public Task&lt;T&gt; 其中 T 是从返回的类型方法。然后你可以做await Task.Run(() =&gt; display_frame());
  • display_frame() 应该返回什么?我做了“public Task display_frame()”但是得到编译错误“不是所有的代码路径都返回一个值”。
  • 所以我返回:return null;
  • return Task.CompletedTask();导致此错误:“不可调用的成员“Task.CompletedTask”不能像方法一样使用。”
  • 对不起,我应该把() 关掉,它是一个属性而不是一个方法,做return Task.CompletedTask; 文档(docs.microsoft.com/en-us/dotnet/api/…

标签: c# uwp xamarin.ios xamarin.uwp


【解决方案1】:

查看代码中的using 语句:

using UIKit;
...
using Windows.UI.Core; 

这不可能发生。 UIKit 是 Xamarin.iOS,特定于平台的命名空间,Windows.UI.Core 是特定于 Windows 平台的命名空间,这两者决不能混合在一个文件中(除了带有 #if 指令的共享项目,但是这里不是这样)。

Xamarin 有助于编写跨平台应用程序,但您仍然无法在不可用的操作系统上使用特定于平台的 API。 Windows 有 Dispatcher 作为在 UI 线程上运行代码的一种方式,但这个概念在 iOS 上不可用,它使用 InvokeOnMainThread 方法代替。

因此,如果您在特定于平台的 iOS 项目中编写代码,则必须使用 iOS API。如果您正在编写特定于平台的 UWP 项目中的代码,则必须使用 UWP API - 像 Dispatcher 这样的东西在那里可以正常工作。

最后,如果您在 .NET Standard 库中编写代码,则不能直接编写任何特定于平台的代码,并且必须使用 dependency injection 定义一个接口,在该接口后面隐藏平台特定 API 的使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2013-10-02
    • 2014-04-22
    • 2017-06-17
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多