简体   繁体   English

几分钟后,C#控制台应用程序的一部分停止工作。 请自己复制并粘贴此控制台应用代码

[英]Part of console app stops working after a few minutes C#. Please copy and paste this console app code for yourself

The app below "runs" for about 2 minutes after entering an IP address (not sure the exact time) and then "stops" running. 输入IP地址(不确定确切时间)后,下面的应用“运行”大约2分钟,然后“停止”运行。 By "stops" I mean it is stuck on this line when i pause the debugger after it has run for 10 minutes: “停止”是指在调试器运行10分钟后暂停调试器时,它停留在该行上:

Any idea why? 知道为什么吗?

EDIT: 编辑:

You can copy and past the code below into a console app and it will run. 您可以将以下代码复制并粘贴到控制台应用程序中,它将运行。 It takes a couple minutes, and after a few iterations, it (usually) gets stuck on message 161. 它需要几分钟,并且经过几次迭代后,(通常)卡在消息161上。

EDIT: The sending portion of this application stops working. 编辑:此应用程序的发送部分停止工作。 But the listening for UDP continues as expected. 但是,UDP侦听仍按预期进行。 See accepted answer on why this is happneing. 有关为什么会发生这种情况,请参见已接受的答案。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;


namespace UDPTest2
{
    class Program
    {
        static string ip;
        static UDPSender sender;
        static UDPListener listener;
        private static bool _quitFlag = false;

        static void Main(string[] args)
        {
            //Console.WriteLine("Enter '1' to listen for UDP messages or '2' to send UDP messages, or 3 for both sending and receiving");
            int choice = 3;
            //if (Int32.TryParse(Console.ReadLine(), out choice))
            //{
                int port = 10001;
                Console.WriteLine("Enter YOUR IP address (include periods)");
                ip = Console.ReadLine();
                switch (choice)
                {
                    case 3: // send and receive from same terminal
                        Task taskReceive = new Task(() =>
                        {
                            listener = new UDPListener(ip, port);
                            listener.StartListener();
                        }, TaskCreationOptions.LongRunning);
                        taskReceive.Start();

                        sender = new UDPSender(ip, port);
                        sender.SendUDPContinuously(100);

                        break;
                    case 4:
                        break;
                    default:
                        Console.WriteLine("the input entered was not understood" + Environment.NewLine);
                        break;
                }
            //}
            //else
            //{
                //Console.WriteLine("Invalid integer input");
            //}
            //Console.WriteLine("press any key to exit");
        }
      Console.ReadLine();
    }

    public class UDPSender
    {
        private Socket s;
        private static byte sequenceNumber = 255;
        private IPAddress toIpAddress;
        private int portNumber;
        private byte lastOctet;         // first part of message byte array
        public UDPSender(string ipAddress, int portNumber)
        {
            s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                ProtocolType.Udp);
            toIpAddress = IPAddress.Parse(ipAddress);
            lastOctet = toIpAddress.GetAddressBytes()[3];
            this.portNumber = portNumber;
        }

        public void SendUDPOnce()
        {
            byte[] sendbuf = new byte[4];
            BuildByteMessage(lastOctet, Encoding.ASCII.GetBytes("PF"), sendbuf); // I can refactor this to just take a CommandParameters.BytesAndCommandEnum
            IPEndPoint ep = new IPEndPoint(toIpAddress, portNumber);
            s.SendTo(sendbuf, ep);
            //Console.WriteLine("Sender: Message sent to the broadcast address: " + toIpAddress + Environment.NewLine + "Sender: contents (first byte is IP_Octet, second is sequenceNumber): " + string.Join(",", sendbuf));
        }

        public void SendUDPContinuously(int delayMiliseconds)
        {
            Timer timerstuff = new Timer(sate => SendUDPOnce(), null, 0, delayMiliseconds);
        }

        private void BuildByteMessage(byte lastOctet, byte[] parameterCommand, byte[] destination)
        {
            byte sequenceNum = CreateNextSequenceByte();
            destination[0] = lastOctet;
            destination[1] = sequenceNum;
            Buffer.BlockCopy(parameterCommand, 0, destination, 2, parameterCommand.Length);
        }

        public byte CreateNextSequenceByte()
        {
            if (sequenceNumber != 255)
            {
                sequenceNumber++;
            }
            else
            {
                sequenceNumber = 0;
            }
            return sequenceNumber;
        }
    }

}

namespace UDPTest2
{
    public class UDPListener
    {
        string ipAddress;
        int listenPort;

        public UDPListener(string ipAddress, int listenPort)
        {
            this.ipAddress = ipAddress;
            this.listenPort = listenPort;
        }

        public void StartListener()
        {
            bool done = false;

            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse(ipAddress), listenPort);

            try
            {
                while (!done)
                {
                    //Console.WriteLine("Receiver: Waiting for broadcast...");

                    //First byte of the received message is the ASCII Mesage type flag: Q=Data, M=Metric, F=Fault. Second byte is the U8 sequence number. Third byte on is the actual data. 
                    byte[] bytes = listener.Receive(ref groupEP);
                    byte[] data = new byte[bytes.Length - 2];
                    Buffer.BlockCopy(bytes, 2, data, 0, bytes.Length - 2);
                    Console.WriteLine("Receiver: broadcast from {0} :\nReceiver: {1}\nReceiver: contents of each byte: " + string.Join(", ", bytes),
                        groupEP.ToString(),
                        Encoding.ASCII.GetString(bytes)); // Or Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
    }
}

Timer timerstuff is a local variable. Timer timerstuff是局部变量。 It could be disposed by the GC at some point. 它可以在某个时候由GC处理。 Make it a field to make it permanent and to keep it alive. 使它成为永久性并保持生命的领域。

public class UDPSender
{
    private Timer _timerstuff;

    ...

    public void SendUDPContinuously(int delayMiliseconds)
    {
        _timerstuff = new Timer(sate => SendUDPOnce(), null, 0, delayMiliseconds);
    }                           

    ...
}

See: Automatic memory management and garbage collection: Releasing Memory (Microsoft Docs) 请参阅: 自动内存管理和垃圾回收:释放内存 (Microsoft Docs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM