我是字典的新手,发现它们非常有用。我有接受多个客户端连接的 ac# 服务器控制台。每次客户端连接时,它都会被添加到服务器字典中。我目前正在使用 .net 3.5(并且不会很快升级)并且使用的字典不是线程安全的也不是静态的。客户通常会自行退出,但我需要实现故障安全。如果客户端没有自行退出,我想使用计时器在 5 分钟后关闭连接。连接关闭后,需要从字典中删除该项目。我将如何使我的字典和计时器工作来实现这一点?我被困住了,已经耗尽了我的资源。我正在使用“_clientSockets.Remove(current)”关闭连接
下面是我目前拥有的字典和计时器的代码片段:
private static Timer aTimer = new System.Timers.Timer(10000);
private static Object thisLock = new Object();
public static void Main()
{
Console.ReadKey();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000 * 60 * 5;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.WriteLine(DateTime.Now);
Console.ReadLine();
Dictionary<int, DateTime> ServDict = new Dictionary<int, DateTime>();
ServDict.Add(9090, DateTime.Now.AddMinutes(5));
ServDict.Add(9091, DateTime.Now.AddMinutes(5));
ServDict.Add(9092, DateTime.Now.AddMinutes(5));
ServDict.Add(9093, DateTime.Now.AddMinutes(5));
ServDict.Add(9094, DateTime.Now.AddMinutes(5));
Console.WriteLine("Time List");
foreach (KeyValuePair<int, DateTime> time in ServDict)
{
Console.WriteLine("Port = {0}, Time in 5 = {1}",
time.Key, time.Value);
}
Console.ReadKey();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The trigger worked, The Elapsed event was raised at {0}", e.SignalTime);
Console.WriteLine(DateTime.Now);
}