下面的应用程序在输入 IP 地址后“运行”约 2 分钟(不确定确切时间),然后“停止”运行。通过“停止”,我的意思是当我在调试器运行 10 分钟后暂停它时,它会卡在这条线上:知道为什么吗?编辑:您可以将下面的代码复制并粘贴到控制台应用程序中,它就会运行。这需要几分钟,经过几次迭代后,它(通常)卡在消息 161 上。编辑: 此应用程序的发送部分停止工作。但是对 UDP 的侦听继续按预期进行。请参阅有关为什么会发生这种情况的公认答案。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; } //}
1 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
Timer timerstuff是局部变量。它可以在某个时候由 GC 处理。使它成为一个领域,使其永久并保持活力。
public class UDPSender
{
private Timer _timerstuff;
...
public void SendUDPContinuously(int delayMiliseconds)
{
_timerstuff = new Timer(sate => SendUDPOnce(), null, 0, delayMiliseconds);
}
...
}
- 1 回答
- 0 关注
- 240 浏览
添加回答
举报
0/150
提交
取消