please enhance this code knowing I'm using C# 7,3 and .Net Framework 4.7.2:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.IO;
using System.Threading;
using System.Threading.Tasks.Dataflow;
using System.Collections.Generic;
using System.Net;
using System.Configuration;
namespace MdfConsoleReader
{
    class Program
    {
        private static readonly string _ServerIP = ConfigurationManager.AppSettings["ServerIP"];
        private static readonly int _ServerPort = int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
        private static readonly string _Username = ConfigurationManager.AppSettings["Username"];
        private static readonly string _Password = ConfigurationManager.AppSettings["Password"];
        private static readonly string _UserType = ConfigurationManager.AppSettings["UserType"];
        private static readonly int _ReconnectDelay = int.Parse(ConfigurationManager.AppSettings["ReconnectDelay"]);
        private static readonly int _BufferSize = int.Parse(ConfigurationManager.AppSettings["BufferSize"]);
        private static readonly int _AuthenticationTimeout = int.Parse(ConfigurationManager.AppSettings["AuthenticationTimeout"]);
        private static readonly int _MessageSenderPort = int.Parse(ConfigurationManager.AppSettings["MessageSenderPort"]);

        private static BufferBlock<string> _MarketDepthBuffer;
        private static BufferBlock<string> _WatchlistBuffer;
        private static BufferBlock<WatchlistMessage> _MessageBuffer;
        private static StringBuilder _IncompleteMessage = new StringBuilder(_BufferSize);
        private static CancellationTokenSource _cts = new CancellationTokenSource();
        private static volatile bool _ShowFormatted = true;
        private static readonly object _ConsoleLock = new object();
        private static readonly SemaphoreSlim _ConnectionSemaphore = new SemaphoreSlim(1, 1);
        private static readonly AutoResetEvent _ReconnectEvent = new AutoResetEvent(false);
        private static volatile bool _IsConnected = false;
        private static readonly IPEndPoint _MessageSenderEndpoint = new IPEndPoint(IPAddress.Loopback, _MessageSenderPort);

        static async Task Main(string[] args)
        {
            Console.WriteLine("Slave Client Starting...");
            AppDomain.CurrentDomain.ProcessExit += OnApplicationExit;
            InitializeBuffers();

            Task keyListenerTask = Task.Run(KeyListener);
            Task connectionMonitorTask = Task.Run(ConnectionMonitor);
            Task messageSenderTask = Task.Run(MessageSender);

            while (!_cts.Token.IsCancellationRequested)
            {
                try
                {
                    await RunClientAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Connection error: {ex.Message}");
                    _IsConnected = false;
                    _ReconnectEvent.Set();
                    await Task.Delay(_ReconnectDelay);
                }
            }

            await Task.WhenAll(keyListenerTask, connectionMonitorTask, messageSenderTask);
        }

        private static void InitializeBuffers()
        {
            var xDataflowOptions = new ExecutionDataflowBlockOptions
            {
                BoundedCapacity = 100000,
                MaxDegreeOfParallelism = Environment.ProcessorCount,
                EnsureOrdered = false
            };

            _MarketDepthBuffer = new BufferBlock<string>(xDataflowOptions);
            _WatchlistBuffer = new BufferBlock<string>(xDataflowOptions);
            _MessageBuffer = new BufferBlock<WatchlistMessage>(xDataflowOptions);
        }

        private static void KeyListener()
        {
            while (!_cts.Token.IsCancellationRequested)
            {
                if (Console.KeyAvailable)
                {
                    var xKey = Console.ReadKey(true);
                    if (xKey.Key == ConsoleKey.T)
                    {
                        _ShowFormatted = !_ShowFormatted;
                        lock (_ConsoleLock)
                        {
                            Console.WriteLine($"\nDisplay mode changed to: {(_ShowFormatted ? "Formatted" : "Raw")}");
                        }
                    }
                }
                Thread.Sleep(100);
            }
        }

        private static async Task ConnectionMonitor()
        {
            while (!_cts.Token.IsCancellationRequested)
            {
                if (!_IsConnected)
                {
                    Console.WriteLine("Connection lost. Waiting for reconnection...");
                    _ReconnectEvent.WaitOne();

                    if (!_cts.Token.IsCancellationRequested)
                    {
                        Console.WriteLine($"Attempting to reconnect in {_ReconnectDelay / 1000} seconds...");
                        await Task.Delay(_ReconnectDelay, _cts.Token);
                    }
                }
                await Task.Delay(1000, _cts.Token);
            }
        }

        private static async Task RunClientAsync()
        {
            using (TcpClient client = new TcpClient())
            {
                await _ConnectionSemaphore.WaitAsync();
                try
                {
                    client.ReceiveBufferSize = _BufferSize;
                    client.SendBufferSize = _BufferSize;

                    Console.WriteLine($"Connecting to {_ServerIP}:{_ServerPort}...");
                    await client.ConnectAsync(_ServerIP, _ServerPort);
                    Console.WriteLine("Connected to server.");

                    using (NetworkStream stream = client.GetStream())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, _BufferSize))
                    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, _BufferSize) { AutoFlush = true })
                    {
                        string serverMessage = await reader.ReadLineAsync();
                        Console.WriteLine($"Server: {serverMessage}");

                        await Task.Delay(1000); // Wait after welcome message

                        if (!await Authenticate(writer, reader))
                        {
                            _IsConnected = false;
                            _ReconnectEvent.Set();
                            return;
                        }

                        _IsConnected = true;
                        await SubscribeToData(writer);

                        var tasks = new[]
                        {
                            ReadMessagesLoop(reader),
                            ProcessMarketDepthMessages(),
                            ProcessWatchlistMessages(),
                            DisplayMessagesLoop()
                        };

                        await Task.WhenAny(tasks);
                    }
                }
                finally
                {
                    _ConnectionSemaphore.Release();
                }
            }
        }

        private static async Task<bool> Authenticate(StreamWriter vWriter, StreamReader vReader)
        {
            try
            {
                string xAuthMessage = $"<Authentication Username=\"{_Username}\" Password=\"{_Password}\" UserType=\"{_UserType}\" UseCompression=\"0\" GlobalSymbology=\"1\"/>";
                await vWriter.WriteLineAsync(xAuthMessage);
                Console.WriteLine("Authentication message sent, waiting for response...");

                using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(_AuthenticationTimeout)))
                {
                    string xResponse = await vReader.ReadLineAsync();
                    Console.WriteLine($"Authentication Response: {xResponse}");

                    if (string.IsNullOrEmpty(xResponse))
                    {
                        Console.WriteLine("No response received from server.");
                        return false;
                    }

                    if (!xResponse.Contains("Value=\"1\""))
                    {
                        Console.WriteLine("Authentication failed. Invalid credentials or response.");
                        return false;
                    }

                    Console.WriteLine("Authentication successful!");
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Authentication error: {ex.Message}");
                return false;
            }
        }

        private static async Task SubscribeToData(StreamWriter vWriter)
        {
            try
            {
                await Task.Delay(500);
                string xWatchlistRequest = "<WatchListStreamRequest Symbol=\"*\" Market=\"*\" />";
                await vWriter.WriteLineAsync(xWatchlistRequest);
                Console.WriteLine("Watchlist subscription request sent.");

                //string xMarketDepthRequest = "<MarketDepthRequest Symbol=\"*\" Market=\"*\" Type=\"MBP\" />";
                //await writer.WriteLineAsync(xMarketDepthRequest);
                //Console.WriteLine("Market depth subscription request sent.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Subscription error: {ex.Message}");
                throw;
            }
        }

        private static async Task ReadMessagesLoop(StreamReader vReader)
        {
            try
            {
                char[] buffer = new char[_BufferSize];
                while (!_cts.Token.IsCancellationRequested && _IsConnected)
                {
                    int bytesRead = await vReader.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        _IsConnected = false;
                        _ReconnectEvent.Set();
                        break;
                    }

                    string data = new string(buffer, 0, bytesRead);
                    await ProcessIncomingDataAsync(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in ReadMessagesLoop: {ex.Message}");
                _IsConnected = false;
                _ReconnectEvent.Set();
            }
        }

        private static async Task ProcessIncomingDataAsync(string vData)
        {
            try
            {
                var messages = ParseMessages(vData);
                foreach (var iMessage in messages)
                {
                    if (iMessage.StartsWith("<WatchlistMessage"))
                    {
                        await _WatchlistBuffer.SendAsync(iMessage);
                    }
                    else if (iMessage.StartsWith("<MarketDepthMessage"))
                    {
                        await _MarketDepthBuffer.SendAsync(iMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in ProcessIncomingData: {ex.Message}");
            }
        }

        private static IEnumerable<string> ParseMessages(string vData)
        {
            lock (_IncompleteMessage)
            {
                _IncompleteMessage.Append(vData);
                var xMessages = new List<string>();
                string xFullData = _IncompleteMessage.ToString();
                int xLastIndex = 0;

                while (true)
                {
                    int xStartWatchlist = xFullData.IndexOf("<WatchlistMessage", xLastIndex);
                    int xStartMarketDepth = xFullData.IndexOf("<MarketDepthMessage", xLastIndex);

                    if (xStartWatchlist == -1 && xStartMarketDepth == -1) break;

                    int start = (xStartWatchlist >= 0 && (xStartMarketDepth == -1 || xStartWatchlist < xStartMarketDepth))
                        ? xStartWatchlist
                        : xStartMarketDepth;

                    string endTag = start == xStartWatchlist ? "</WatchlistMessage>" : "</MarketDepthMessage>";
                    int end = xFullData.IndexOf(endTag, start);

                    if (end == -1) break;

                    string xMessage = xFullData.Substring(start, end - start + endTag.Length);
                    xMessages.Add(xMessage);
                    xLastIndex = end + endTag.Length;
                }

                if (xLastIndex > 0)
                {
                    _IncompleteMessage.Clear();
                    _IncompleteMessage.Append(xFullData.Substring(xLastIndex));
                }

                return xMessages;
            }
        }

        private static async Task ProcessMarketDepthMessages()
        {
            while (await _MarketDepthBuffer.OutputAvailableAsync())
            {
                string xMessage = await _MarketDepthBuffer.ReceiveAsync();
                await ProcessMessageAsync(xMessage, true);
            }
        }

        private static async Task ProcessWatchlistMessages()
        {
            while (await _WatchlistBuffer.OutputAvailableAsync())
            {
                string xMessage = await _WatchlistBuffer.ReceiveAsync();
                await ProcessMessageAsync(xMessage, false);
            }
        }

        private static async Task ProcessMessageAsync(string vMessage, bool vIsMarketDepth)
        {
            try
            {
                XElement xml = XElement.Parse(vMessage);
                if (!_ShowFormatted)
                {
                    lock (_ConsoleLock)
                    {
                        Console.WriteLine($"Processing {(vIsMarketDepth ? "MarketDepth" : "Watchlist")}: {vMessage}");
                    }
                }
                else
                {
                    await DisplayFormattedMessageAsync(xml, vIsMarketDepth);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing message: {ex.Message}");
            }
        }

        private static async Task DisplayFormattedMessageAsync(XElement vXml, bool vIsMarketDepth)
        {
            await Task.Run(() =>
            {
                lock (_ConsoleLock)
                {
                    Console.ForegroundColor = vIsMarketDepth ? ConsoleColor.Yellow : ConsoleColor.Green;
                    if (vIsMarketDepth)
                    {
                        DisplayFormattedMarketDepth(vXml);
                    }
                    else
                    {
                        DisplayFormattedWatchlist(vXml);
                    }
                    Console.ResetColor();
                }
            });
        }

        private static void DisplayFormattedMarketDepth(XElement vXml)
        {
            string xType = vXml.Attribute("Type")?.Value ?? "Unknown";
            string xSymbol = vXml.Attribute("Symbol")?.Value ?? "Unknown";
            string xMarket = vXml.Attribute("Market")?.Value ?? "Unknown";

            Console.WriteLine($"\n=== Market Depth: {xSymbol} ({xMarket}) ===");
            Console.WriteLine($"Type: {xType}");

            foreach (var iDepthSection in vXml.Elements())
            {
                Console.WriteLine($"\n{iDepthSection.Name.LocalName}:");
                Console.WriteLine("Price\tQuantity\tVolume");
                Console.WriteLine("--------------------------------");

                foreach (var depthData in iDepthSection.Elements("DepthData"))
                {
                    string xPrice = depthData.Attribute("col1")?.Value ?? "N/A";
                    string xQuantity = depthData.Attribute("col2")?.Value ?? "N/A";
                    string xVolume = depthData.Attribute("col3")?.Value ?? "N/A";
                    Console.WriteLine($"{xPrice}\t{xQuantity}\t\t{xVolume}");
                }
            }
        }

        private static void DisplayFormattedWatchlist(XElement vXml)
        {
            foreach (var iRow in vXml.Elements("Row"))
            {
                // Create and store MBO, MBP, and BM messages
                string symbol = iRow.Attribute("symbol")?.Value ?? "N/A";

                string xMboMessage = $"{symbol}|MBO|{iRow.Attribute("MBO")?.Value ?? "N/A"}";
                string xMbpMessage = $"{symbol}|MBP|{iRow.Attribute("MBP")?.Value ?? "N/A"}";
                string xBmMessage = $"{symbol}|BM|{iRow.Attribute("offer")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("offerVol")?.Value ?? "N/A"}|{iRow.Attribute("avgPrice")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("bid")?.Value ?? "N/A"}|{iRow.Attribute("bidVol")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("high")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("low")?.Value ?? "N/A"}|{iRow.Attribute("trades")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("mValue")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("mVolume")?.Value ?? "N/A"}|{iRow.Attribute("vChange")?.Value ?? "N/A"}|" +
                                   $"{GetSign(iRow.Attribute("vChange")?.Value)}|" +
                                   $"{iRow.Attribute("high52")?.Value ?? "N/A"}|{iRow.Attribute("low52")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("MaxPrice")?.Value ?? "N/A"}|{iRow.Attribute("MinPrice")?.Value ?? "N/A"}|" +
                                   $"{iRow.Attribute("OpenPrice")?.Value ?? "N/A"}|{iRow.Attribute("pClose")?.Value ?? "N/A"}||||||||||||";

                Console.WriteLine("\n=== Watchlist Update ===");
                Console.WriteLine($"Symbol: {symbol}");
                Console.WriteLine($"Description: {iRow.Attribute("description")?.Value ?? "N/A"}");
                Console.WriteLine($"Current Price: {iRow.Attribute("cPrice")?.Value ?? "N/A"}");
                Console.WriteLine($"Previous Close: {iRow.Attribute("pClose")?.Value ?? "N/A"}");
                Console.WriteLine($"Bid: {iRow.Attribute("bid")?.Value ?? "N/A"} (Vol: {iRow.Attribute("bidVol")?.Value ?? "N/A"})");
                Console.WriteLine($"Offer: {iRow.Attribute("offer")?.Value ?? "N/A"} (Vol: {iRow.Attribute("offerVol")?.Value ?? "N/A"})");
                Console.WriteLine($"Change: {iRow.Attribute("percent")?.Value ?? "N/A"}%");
                Console.WriteLine($"Market Volume: {iRow.Attribute("mVolume")?.Value ?? "N/A"}");
                Console.WriteLine($"Market Value: {iRow.Attribute("mValue")?.Value ?? "N/A"}");
                Console.WriteLine($"MBO: {xMboMessage}");
                Console.WriteLine($"MBP: {xMbpMessage}");
                Console.WriteLine($"BM: {xBmMessage}");

                // Add messages to the buffer
                _MessageBuffer.Post(new WatchlistMessage { Symbol = symbol, MessageType = "MBO", Content = xMboMessage });
                _MessageBuffer.Post(new WatchlistMessage { Symbol = symbol, MessageType = "MBP", Content = xMbpMessage });
                _MessageBuffer.Post(new WatchlistMessage { Symbol = symbol, MessageType = "BM", Content = xBmMessage });

                Console.WriteLine("------------------------");
            }
        }

        private static string GetSign(string vValue)
        {
            if (double.TryParse(vValue, out double xResult))
            {
                if (xResult > 0) return "1";
                if (xResult < 0) return "-1";
                return "0";
            }
            return "N/A";
        }

        private static async Task DisplayMessagesLoop()
        {
            var xDisplayTasks = new[]
            {
                ProcessMarketDepthMessages(),
                ProcessWatchlistMessages()
            };

            await Task.WhenAll(xDisplayTasks);
        }

        private static async Task MessageSender()
        {
            using (var udpClient = new UdpClient())
            {
                while (!_cts.Token.IsCancellationRequested)
                {
                    try
                    {
                        WatchlistMessage xMessage = await _MessageBuffer.ReceiveAsync(_cts.Token);
                        byte[] xMessageBytes = Encoding.UTF8.GetBytes(xMessage.Content);
                        await udpClient.SendAsync(xMessageBytes, xMessageBytes.Length, _MessageSenderEndpoint);
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error sending message: {ex.Message}");
                    }
                }
            }
        }

        protected static void OnApplicationExit(object sender, EventArgs e)
        {
            _IsConnected = false;
            _cts.Cancel();
            _ReconnectEvent.Set();
            _ConnectionSemaphore.Dispose();
            _ReconnectEvent.Dispose();
        }
    }
}