если у меня свич флаг 2 или 3 я хочу отправлять один раз данные по udp
using System;
using System.Net;
using System.Threading.Tasks;
using DataType.ExternalSystems.Psy;
using Newtonsoft.Json;
using TheRepresentationOfTheDateInPsycholophysiology.Models;

namespace TheRepresentationOfTheDateInPsycholophysiology.Services
{
    public class PsyDataSenderReceiver
    {
        private static PsyDataSenderReceiver _instance;
        private static readonly object _lock = new object();

        private readonly UdpSendReceiveService<PilotMetrics, PilotMetrics> _udpSendReceiveService;
        private readonly DataTransferService _dataTransferService;

        private bool _isRunning;

        // Полученные данные
        public PilotMetrics ReceivedOutputs { get; private set; }

        // Данные для отправки
        public PilotMetrics SendOutputs { get; private set; }

        // Событие для уведомления о обновлении данных
        public event Action<PilotMetrics> DataUpdated;

        // Флаг для модификации данных
        public int FlagSwitch { get; set; }

        /// <summary>
        /// Приватный конструктор для реализации паттерна Singleton.
        /// </summary>
        private PsyDataSenderReceiver(IPAddress ipAddress, int sendPort, int receivePort, DataTransferService dataTransferService)
        {
            _udpSendReceiveService = new UdpSendReceiveService<PilotMetrics, PilotMetrics>(ipAddress, sendPort, receivePort);
            _dataTransferService = dataTransferService;

            // Подписка на событие получения данных из DataTransferService
            _dataTransferService.DataReceived += OnDataReceived;

            // Инициализация данных
            SendOutputs = new PilotMetrics();
            ReceivedOutputs = InitPilotMetrics();
        }

        /// <summary>
        /// Получение единственного экземпляра класса (Singleton).
        /// </summary>
        public static PsyDataSenderReceiver GetInstance(IPAddress ipAddress, int sendPort, int receivePort, DataTransferService dataTransferService)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new PsyDataSenderReceiver(ipAddress, sendPort, receivePort, dataTransferService);
                    }
                }
            }
            return _instance;
        }

        /// <summary>
        /// Запуск работы сервиса.
        /// </summary>
        public void Start()
        {
            if (_isRunning)
                return;

            _isRunning = true;
            //_udpSendReceiveService.StartReceiving(); // Запуск приёма данных через UDP, если необходимо
        }

        /// <summary>
        /// Остановка работы сервиса.
        /// </summary>
        public void Stop()
        {
            if (!_isRunning)
                return;

            _isRunning = false;
            //_udpSendReceiveService.StopReceiving();
            _udpSendReceiveService.Dispose();
        }

        /// <summary>
        /// Обработчик приема данных из DataTransferService.
        /// </summary>
        private async void OnDataReceived(string sourceName, string data)
        {
            if (!_isRunning)
                return;

            try
            {
                // Десериализация полученных данных
                var receivedData = JsonConvert.DeserializeObject<PilotMetrics>(data);
                //if (receivedData is null)
                //{
                //    Console.WriteLine($"Получены некорректные данные из {sourceName}.");
                //    return;
                //}

                // Обновление полученных данных
                ReceivedOutputs = receivedData;

                // Модификация данных в зависимости от флага
                SendOutputs = ModifyOutputs(receivedData);

                // Установка данных для отправки
                _udpSendReceiveService.DataToSend = SendOutputs;

                // Отправка данных через UDP
                await _udpSendReceiveService.SendAsync();

                // Уведомление подписчиков о получении новых данных
                DataUpdated?.Invoke(ReceivedOutputs);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"Ошибка десериализации данных из {sourceName}: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ошибка при обработке данных из {sourceName}: {ex.Message}");
            }
        }

        /// <summary>
        /// Модификация полученных данных на основе значения FlagSwitch.
        /// </summary>
        private PilotMetrics ModifyOutputs(PilotMetrics receivedData)
        {
            // Создание копии полученных данных
            var modifiedData = new PilotMetrics
            {
                Source = receivedData.Source,
                Timestamp = receivedData.Timestamp,
                Version = receivedData.Version,
                IsECGValid = receivedData.IsECGValid,
                HR = receivedData.HR,
                RR = receivedData.RR,
                BR = receivedData.BR,
                SI = receivedData.SI,
                CardiovascularCenterState = receivedData.CardiovascularCenterState,
                IsEEGValid = receivedData.IsEEGValid,
                EEGFrequencyInterval = receivedData.EEGFrequencyInterval,
                EEGLastPoint = receivedData.EEGLastPoint,
                SpectrumPower = receivedData.SpectrumPower,
                AlertnessLevel = receivedData.AlertnessLevel,
                AudioEngagement = receivedData.AudioEngagement,
                CognitivePerformanceIndex = receivedData.CognitivePerformanceIndex,
                IsGDAValid = receivedData.IsGDAValid,
                IsEyesClosed = receivedData.IsEyesClosed,
                PhysiologicalState = receivedData.PhysiologicalState,
                PsychophysiologicalState = receivedData.PsychophysiologicalState,
                IsNotInCabin = receivedData.IsNotInCabin
            };

            // Модификация данных в зависимости от флага
            if (FlagSwitch == 2)
            {
                MakeGoodOutputs(ref modifiedData);
            }
            else if (FlagSwitch == 3)
            {
                MakeBadOutputs(ref modifiedData);
            }

            return modifiedData;
        }

        /// <summary>
        /// Формирование "хороших" данных.
        /// </summary>
        private void MakeGoodOutputs(ref PilotMetrics outputs)
        {
            outputs.HR = 75;
            outputs.EEGLastPoint = 0.35f;
            outputs.PhysiologicalState = 0;
            outputs.PsychophysiologicalState = 0;
        }

        /// <summary>
        /// Формирование "плохих" данных.
        /// </summary>
        private void MakeBadOutputs(ref PilotMetrics outputs)
        {
            outputs.HR = 0;
            outputs.EEGLastPoint = 0f;
            outputs.PhysiologicalState = 1;
            outputs.PsychophysiologicalState = 1;
        }

        /// <summary>
        /// Инициализация данных по умолчанию.
        /// </summary>
        private PilotMetrics InitPilotMetrics()
        {
            return new PilotMetrics
            {
                Source = string.Empty,
                Timestamp = 0,
                Version = 1,
                IsECGValid = false,
                HR = 0,
                RR = 0,
                BR = 0,
                SI = 0f,
                CardiovascularCenterState = 0,
                IsEEGValid = false,
                EEGFrequencyInterval = 0,
                EEGLastPoint = 0f,
                SpectrumPower = new float[0],
                AlertnessLevel = 0,
                AudioEngagement = 0f,
                CognitivePerformanceIndex = 0f,
                IsGDAValid = false,
                IsEyesClosed = false,
                PhysiologicalState = 0,
                PsychophysiologicalState = 0,
                IsNotInCabin = false
            };
        }
    }
}