下面的應(yīng)用程序在輸入 IP 地址后“運行”約 2 分鐘(不確定確切時間),然后“停止”運行。通過“停止”,我的意思是當(dāng)我在調(diào)試器運行 10 分鐘后暫停它時,它會卡在這條線上:知道為什么嗎?編輯:您可以將下面的代碼復(fù)制并粘貼到控制臺應(yīng)用程序中,它就會運行。這需要幾分鐘,經(jīng)過幾次迭代后,它(通常)卡在消息 161 上。編輯: 此應(yīng)用程序的發(fā)送部分停止工作。但是對 UDP 的偵聽繼續(xù)按預(yù)期進(jìn)行。請參閱有關(guān)為什么會發(fā)生這種情況的公認(rèn)答案。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貢獻(xiàn)1833條經(jīng)驗 獲得超4個贊
Timer timerstuff是局部變量。它可以在某個時候由 GC 處理。使它成為一個領(lǐng)域,使其永久并保持活力。
public class UDPSender
{
private Timer _timerstuff;
...
public void SendUDPContinuously(int delayMiliseconds)
{
_timerstuff = new Timer(sate => SendUDPOnce(), null, 0, delayMiliseconds);
}
...
}
- 1 回答
- 0 關(guān)注
- 264 瀏覽
添加回答
舉報
0/150
提交
取消