我在c#中遇到计时器控制问题。请参阅代码中的解释,
Onform_Load
{
// On form load initiating the timer control, to verify whether the server connection is established or not
timer2 = new Timer();
timer2.Interval = 1000;
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
Socket sock = Sockets.CreateTCPSocket(IPAddress, Convert.ToInt32(Port));
client = new ClientInfo(sock, false); // Don't start receiving yet
client.OnReadBytes += new ConnectionReadBytes(ReadData);
client.OnClose += new ConnectionClosed(OnClose);
try
{
client.BeginReceive();
OnConnected();
}
catch
{
OnClose();
}
}
void OnConnected()
{
//connection established message
}
void OnClose(ClientInfo clnt)
{
//Connection Closed
}
通过使用上述 timer2_Tick 事件,无论是否建立连接,应用程序都会不断访问服务器。
在建立连接时 停止计时器 。
和
启动计时器连接关闭时。
见下面的代码:
void OnConnected()
{
timer2.Stop();
//connection established message
}
void OnClose(ClientInfo clnt)
{
timer2.Start();// here i tried timer2.Enabled and intiated the interval. but it is not working
//Connection Closed
}
任何人都可以帮助我,如何在基于条件的情况下启动和停止计时器,
提前致谢。