首页 > 解决方案 > UWP“当前上下文中不存在名称调度程序”

问题描述

在 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;
}

最新方法的错误

在此处输入图像描述

标签: c#uwpxamarin.iosxamarin.uwp

解决方案


查看代码中的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 库中编写代码,则不能直接编写任何特定于平台的代码,并且必须使用依赖注入来定义一个接口,在该接口后面隐藏平台特定 API 的使用。


推荐阅读