Xamarin 无法从异步获取实例

2024-05-13

我编写了一个通过蓝牙连接到 ESP32 的 Xamarin.Forms 应用程序。现在我想从 MainPage.xaml 页面的 CustomControl.JoystickControl 获取值。

我已经这样尝试过了:

MainPage.xaml.cs:

 public partial class MainPage : ContentPage
{

    public static Bluetooth.IBth bth = new Bluetooth.Bth();
    public MainPage()
    {
        InitializeComponent();

        Task.Run(async () => bth.Start("mecanumWheelRobot", 200, false));


    }

    public CustomControls.JoystickControl JoystickControlElement
    {
        get { return JoystickControl; }
    }
    public CustomControls.JoystickControl JoystickControlElement1
    {
        get { return JoystickControl1; }
    }
}

现在我想从以下异步函数获取 JoystickControlElement:

var mainpage = new Views.MainPage();

字符串测试 = mainpage.test;(这两行就是问题所在)

class Bth : IBth
{

    private CancellationTokenSource _ct { get; set; }
    

    const int RequestResolveError = 1000;

    public Bth()
    {
    }

    public void Start(string name, int sleepTime = 200, bool readAsCharArray = false)
    {

        Task.Run(async () => loop(name, sleepTime, readAsCharArray));
    }



    private async Task loop(string name, int sleepTime, bool readAsCharArray)
    {

        BluetoothDevice device = null;
        BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
        BluetoothSocket BthSocket = null;

        _ct = new CancellationTokenSource();
        while (_ct.IsCancellationRequested == false)
        {

            try
            {
                Thread.Sleep(sleepTime);

                adapter = BluetoothAdapter.DefaultAdapter;

                if (adapter == null)
                    System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
                else
                    System.Diagnostics.Debug.WriteLine("Adapter found!!");

                if (!adapter.IsEnabled)
                    System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled.");
                else
                    System.Diagnostics.Debug.WriteLine("Adapter enabled!");

                System.Diagnostics.Debug.WriteLine("Try to connect to " + name);

                foreach (var bd in adapter.BondedDevices)
                {
                    System.Diagnostics.Debug.WriteLine("Paired devices found: " + bd.Name.ToUpper());
                    if (bd.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
                    {

                        System.Diagnostics.Debug.WriteLine("Found " + bd.Name + ". Try to connect with it!");
                        device = bd;
                        break;
                    }
                }

                if (device == null)
                {
                    System.Diagnostics.Debug.WriteLine("Named device not found.");
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        // Code to run on the main thread
                    });
                }
                else
                {
                    UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
                    if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
                        BthSocket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
                    else
                        BthSocket = device.CreateRfcommSocketToServiceRecord(uuid);

                    if (BthSocket != null)
                    {


                        //Task.Run ((Func<Task>)loop); /*) => {
                        await BthSocket.ConnectAsync();


                        if (BthSocket.IsConnected)
                        {
                            MainThread.BeginInvokeOnMainThread(() =>
                            {
                                service.toast.toastSuccess("Connected!");
                                // Code to run on the main thread
                                //pages.bluetoothBarcodeScan.connectedScanner();
                            });
                            System.Diagnostics.Debug.WriteLine("Connected!");


                                MainThread.BeginInvokeOnMainThread(() =>
                                {
                                    service.toast.toastSuccess("Writing!");
                                    // Code to run on the main thread
                                    //
                                });
                                while (_ct.IsCancellationRequested == false)
                                {

                                    var mainpage = new Views.MainPage();
                                    string test = mainpage.test;
                                    var bytes = Encoding.ASCII.GetBytes("{test}-");
                                    BthSocket.OutputStream.Write(bytes, 0, bytes.Length);
                                    Thread.Sleep(100);

                                }

                                System.Diagnostics.Debug.WriteLine("Exit the inner loop");

                        }
                    }
                    else
                        System.Diagnostics.Debug.WriteLine("BthSocket = null");

                }


            }
            catch(Exception ex)
            {
                    service.toast.toastSuccess(ex.Message);
                }

            finally
            {
                if (BthSocket != null)
                    BthSocket.Close();
                device = null;
                adapter = null;
            }
        }

        System.Diagnostics.Debug.WriteLine("Exit the external loop");
    }
    public void Cancel()
    {
        if (_ct != null)
        {
            System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
            _ct.Cancel();
            MainThread.BeginInvokeOnMainThread(() =>
            {
                service.toast.toastError("Disconnected");
                // Code to run on the main thread
            });
        }
    }

    public async Task<string> GetData()
    {
            var mainpage = new Views.MainPage();
            string test = mainpage.test;
            return "1";
    }


        public ObservableCollection<string> PairedDevices()
    {
        BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
        ObservableCollection<string> devices = new ObservableCollection<string>();

        foreach (var bd in adapter.BondedDevices)
            devices.Add(bd.Name);

        return devices;
    }


    #endregion
}

当涉及到这一行时,异步函数总是从新开始。

我应该如何获取变量?


您可以更改构造函数方法,例如:

  public Bth(string txt)
    {}

然后通过主页.测试 like:

public static Bluetooth.IBth bth = new Bluetooth.Bth(txt);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xamarin 无法从异步获取实例 的相关文章

  • C++:无法使用scoped_allocator_adaptor传播polymorphic_allocator

    我有一个vector
  • Signalr 在生产服务器中总是陷入长轮询

    当我在服务器中托管应用程序时 它会检查服务器端事件并始终回退到长轮询 服务器托管环境为Windows Server 2012 R1和IIS 7 5 无论如何 我们是否可以解决这个问题 https cloud githubuserconten
  • 在 Xamarin Android 中将图像从 URL 异步加载到 ImageView 中

    我有一个包含多个项目的 ListView 列表中的每个项目都应该有一个与之关联的图像 我创建了一个数组适配器来保存每个列表项并具有我希望加载的图像的 url 我正在尝试使用 Web 请求异步加载图像 并设置图像并在加载后在视图中更新它 但视
  • fgets() 和 Ctrl+D,三次才能结束?

    I don t understand why I need press Ctrl D for three times to send the EOF In addition if I press Enter then it only too
  • 如何在 WPF RichTextBox 中跟踪 TextPointer?

    我正在尝试了解 WPF RichTextBox 中的 TextPointer 类 我希望能够跟踪它们 以便我可以将信息与文本中的区域相关联 我目前正在使用一个非常简单的示例来尝试弄清楚发生了什么 在 PreviewKeyDown 事件中 我
  • 如何针对 Nancy 中的 Active Directory 进行身份验证?

    这是一篇过时的文章 但是http msdn microsoft com en us library ff650308 aspx paght000026 step3 http msdn microsoft com en us library
  • c# Asp.NET MVC 使用FileStreamResult下载excel文件

    我需要构建一个方法 它将接收模型 从中构建excel 构建和接收部分完成没有问题 然后使用内存流导出 让用户下载它 不将其保存在服务器上 我是 ASP NET 和 MVC 的新手 所以我找到了指南并将其构建为教程项目 public File
  • 按字典顺序对整数数组进行排序 C++

    我想按字典顺序对一个大整数数组 例如 100 万个元素 进行排序 Example input 100 21 22 99 1 927 sorted 1 100 21 22 927 99 我用最简单的方法做到了 将所有数字转换为字符串 非常昂贵
  • 使用 LINQ 查找列表中特定类型的第一个元素

    使用 LINQ 和 C 在元素列表中查找特定类型的第一个项目的最短表示法是什么 var first yourCollection OfType
  • 线程、进程和 Application.Exit()

    我的应用程序由主消息循环 GUI 和线程 Task Factory 组成 在线程中我调用一些第三方应用程序var p new Process 但是当我调用Application Exit 在消息循环中 我可以看到在线程中启动的进程仍在内存中
  • Windows 10 中 Qt 桌面应用程序的缩放不当

    我正在为 Windows 10 编写一个简单的 Qt Widgets Gui 应用程序 我使用的是 Qt 5 6 0 beta 版本 我遇到的问题是它根本无法缩放到我的 Surfacebook 的屏幕上 这有点难以判断 因为 SO 缩放了图
  • 更改窗口的内容 (WPF)

    我创建了一个简单的 WPF 应用程序 它有两个 Windows 用户在第一个窗口中填写一些信息 然后单击 确定 这会将他们带到第二个窗口 这工作正常 但我试图将两个窗口合并到一个窗口中 这样只是内容发生了变化 我设法找到了这个更改窗口内容时
  • 网络参考共享类

    我用 Java 编写了一些 SOAP Web 服务 在 JBoss 5 1 上运行 其中两个共享一个类 AddressTO Web 服务在我的 ApplycationServer 上正确部署 一切都很顺利 直到我尝试在我的 C 客户端中使用
  • C 中的位移位

    如果与有符号整数对应的位模式右移 则 1 vacant bit will be filled by the sign bit 2 vacant bit will be filled by 0 3 The outcome is impleme
  • 可空属性与可空局部变量

    我对以下行为感到困惑Nullable types class TestClass public int value 0 TestClass test new TestClass Now Nullable GetUnderlyingType
  • 什么是 C 语言的高效工作流程? - Makefile + bash脚本

    我正在开发我的第一个项目 该项目将跨越多个 C 文件 对于我的前几个练习程序 我只是在中编写了我的代码main c并使用编译gcc main c o main 当我学习时 这对我有用 现在 我正在独自开展一个更大的项目 我想继续自己进行编译
  • 已过时 - OpenCV 的错误模式

    我正在使用 OpenCV 1 进行一些图像处理 并且对 cvSetErrMode 函数 它是 CxCore 的一部分 感到困惑 OpenCV 具有三种错误模式 叶 调用错误处理程序后 程序终止 Parent 程序没有终止 但错误处理程序被调
  • 如何在内存中存储分子?

    我想将分子存储在内存中 这些可以是简单的分子 Methane CH4 C H bond length 108 7 pm H H angle 109 degrees But also more complex molecules like p
  • 角度 2 ngIf 与可观察?

    我有一个非常简单的服务 它的工作是从 api authenticate url 获取 200 或 401 auth service ts Injectable export class AuthService constructor pri
  • 将 viewbag 从操作控制器传递到部分视图

    我有一个带有部分视图的 mvc 视图 控制器中有一个 ActionResult 方法 它将返回 PartialView 因此 我需要将 ViewBag 数据从 ActionResult 方法传递到 Partial View 这是我的控制器

随机推荐

  • 如何防止两个卷声明在 Kubernetes 上声明同一个卷?

    在 GKE 上的 Kubernetes 集群上 我有以下持久卷声明 PVC kind PersistentVolumeClaim apiVersion v1 metadata name registry spec accessModes R
  • 图标和导航视图之间的左边距

    我必须在图标和图标之间添加左边距NavigationView 如下图中箭头所示 我知道根据谷歌规范 这个边距必须有16dp但我需要改变它 我努力了
  • Unix 纪元时间转 Java Date 对象

    我有一个包含以下内容的字符串UNIX 纪元时间 https en wikipedia org wiki Unix time 我需要将其转换为 Java Date 对象 String date 1081157732 DateFormat df
  • 使用 jquery 时出现控制台错误 - Uncaught TypeError: Object # has no method

    我尝试使用以下 js 添加类或 css 样式 但出现控制台错误 var i 0 question i addClass show 收到以下控制台日志错误 Uncaught TypeError Object has no method add
  • C++ 克隆惯用语中协变返回类型的用处?

    通常的克隆习惯使用协变返回类型 struct Base virtual Base clone struct Derived public Base Derived clone 我读过一些内容 大意是协变返回类型是 C 后来添加的 较旧的编译
  • 获取传单地图放大时的标记列表

    我是传单新手 我已按照以下步骤设置了地图https github com Asymmetrik ngx leaflet https github com Asymmetrik ngx leaflet 我正在尝试获取地图放大区域中的标记列表
  • 自定义 OpenVPN iOS 客户端 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我正在开发一个自定义 iOS OpenVPN 客户端 我找到了这个原生 OpenVPN 客户端核心源码https staging op
  • 通过ajax POST提交两次表单

    插入到mysql using php通过文件调用AJAX 前insert语句php代码执行select查询到查找重复记录并继续insert statement Issue 从ajax调用php文件时 它执行了两次并得到作为重复记录的响应 好
  • 在 Chrome 扩展中创建隐藏的 iframe

    是否可以在 google chrome 扩展中的 background html 页面上创建一个 iframe 并让它向网站发出请求 我不确定该扩展程序到底是如何工作的 chrome 会自动忽略所有显示标签还是会以不可见的方式运行它 它会正
  • 使用经度和纬度查找给定距离内的所有附近客户

    我有一个包含客户经度和纬度的数据库 我有一个搜索表单 用户将在其中输入日志 纬度 距离下拉列表包含 50 英里 100 英里 当用户单击搜索时 我想编写一个 linq 查询从数据库中获取此距离半径内的所有客户 如何使用 C 和 linq 来
  • jQuery UI 选项卡 - 将选项卡绑定到同一页面上的链接

    我正在尝试将选项卡绑定到同一页面上的链接 但我是 jQuery 的新手 需要一些帮助 我的选项卡使用 jQuery UI 站点的代码 但是 如何绑定同一页面侧边栏中的链接呢
  • 在 git 子模块中签出分支

    如何从子模块内更改分支 当我跑步时git branch从子模块内 我看到以下输出 gt git branch HEAD detached from 229a7b2 master 我如何将自己置于一个新的分支上 喜欢development 只
  • 将命令行参数传递给 emscripten 生成的应用程序

    当使用 Emscripten 编译 C 程序时 会生成一个 HTML 页面来显示程序的结果 我想知道如何将命令行参数传递给应用程序 例如 对于原始的 C 程序 它是 bfs 32 1 我能够通过向生成的 html 文件添加一行来传递命令行参
  • 平衡两轮机器人而不使其向前/向后漂移

    我正在尝试设计一个控制器来平衡 2 轮机器人 约 13 公斤 并使其能够抵抗外力 例如 如果有人踢它 它不应该掉落 也不应该无限期地向前 向后漂移 我对大多数控制技术 LQR 滑模控制 PID 等 都很有经验 但我在网上看到大多数人使用 L
  • Mongoid 命名范围比较同一文档中的两个时间字段

    我需要在 Mongoid 中创建一个命名范围来比较同一文档中的两个时间字段 例如 scope foo where gt updated at gt gt checked at 这显然不会像它对待的那样起作用 checked at作为一个符号
  • MySQL:查询中周数的周日期范围

    我有一个看起来像这样的数据库表 id clock info 1 1262556754 some info 2 1262556230 some other info 3 1262556988 and another 4 1262555678
  • Haskell - 用防护罩替换外壳

    我想知道在这部分代码中是否可以用守卫替换 case 语句 firstFunction String gt Maybe MyType secondFunction MyType gt Integer myFunction String gt
  • 保存和恢复陷阱状态?管理多个陷阱处理程序的简单方法?

    有什么好的方法可以覆盖bash陷阱处理程序不会永久破坏可能已设置或尚未设置的现有处理程序 动态管理任意陷阱例程链怎么样 有没有办法保存陷阱处理程序的当前状态 以便以后可以恢复 在 Bash 中保存和恢复陷阱处理程序状态 我将提交以下堆栈实现
  • Tweepy 流式传输错误

    我正在尝试使用 tweepy 和 textblob 分析推文的情绪 我执行了 pip install tweepy 并且安装成功 但出现以下错误 错误信息 文件 C Users joshey Desktop sent py 第 2 行 位于
  • Xamarin 无法从异步获取实例

    我编写了一个通过蓝牙连接到 ESP32 的 Xamarin Forms 应用程序 现在我想从 MainPage xaml 页面的 CustomControl JoystickControl 获取值 我已经这样尝试过了 MainPage xa