CancellationTokenSource 配合task 用法

using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Zhaoxi.Upper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private double _value;
        // 需要C#代码进行值更新,并且通知到页面
        public double Value
        {
            get { return _value; }
            set
            {
                _value = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
            }
        }

        CancellationTokenSource cts = new CancellationTokenSource();
        Task Task = null;
        IManagedMqttClient client = null;
        bool state = false;
        public MainWindow()
        {
            InitializeComponent();
            // 设置数据源
            this.DataContext = this;

            // 开始执行PLC点位获取动作
            // 连接到PLC
            S7.Net.Plc plc = new S7.Net.Plc(S7.Net.CpuType.S7200Smart, "192.168.2.1", 102, 0, 1);
            plc.Open();
            // 持续获取点位数据
            //Thread thread = new Thread(() => { });
            //thread.IsBackground = true;
            Task = Task.Run(async () =>
            {
                while (!cts.IsCancellationRequested)
                {
                    await Task.Delay(500);
                    // 200SmartPLC里面   VW0  -》 666
                    Value = double.Parse(plc.Read("DB1.DBW0").ToString());

                    // 如果MQTT客户端连接成功,那么开始分发数据
                    if (state)
                    {
                        // 当拿到最新的点位数据后,由MQTT客户端对象提交上去
                        // 主题  
                        // 负载   打包一起发   Json   
                        DataEntity dataEntity = new DataEntity();
                        dataEntity.DeviceId = 123;
                        dataEntity.Points.Add(new PointEntity { PropId = 3, Value = Value });
                        client.PublishAsync("A/A/A", System.Text.Json.JsonSerializer.Serialize(dataEntity));
                    }
                }
            }, cts.Token);


            MqttClient();
        }

        protected override void OnClosed(EventArgs e)
        {
            cts.Cancel();
            Task.WaitAll(new Task[] { Task });
        }

        public event PropertyChangedEventHandler? PropertyChanged;


        private void MqttClient()
        {
            // 服务器相关配置
            // 192.168.151.137  1883   admin   123456
            // Client ID
            // 实例化一个客户端对象 
            client = new MqttFactory().CreateManagedMqttClient();
            client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
            {
                state = true;
            });
            IMqttClientOptions clientOptions = new MqttClientOptionsBuilder()
                .WithClientId(Guid.NewGuid().ToString())
                .WithTcpServer("192.168.151.137", 1883)
                .WithCredentials("admin", "123456")
                .Build();

            IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
                .WithClientOptions(clientOptions)
                .Build();
            client.StartAsync(options);// 连接到某个服务器
        }
    }

    class DataEntity
    {
        public int DeviceId { get; set; }
        public List<PointEntity> Points { get; set; } = new List<PointEntity>();
    }
    class PointEntity
    {
        public int PropId { get; set; }
        public double Value { get; set; }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值