当我举起timer.Start()事件时,Timer不会启动

时间:2016-07-01 03:46:12

标签: c# winforms timer

这是代码块。我将在下面解释详情。

public static bool isConnected;
    public MasterClient()    //Master Constructor
    {
         timer1.Interval = 1000;
         isConnected = false;
    }

    private void connectCallback(IAsyncResult ar)
    {
        try
        {

            _ClientSocket.EndConnect(ar);

            //Global.Meuser = Environment.MachineName;
            BeginReceive();
            Invoke((MethodInvoker)delegate
            {
                tslStatus.Text = "Connected";
                btnConnect.Text = "Disconnect";

                tslStatus.Image = Image.FromFile(Global.path + @"\image\status\online.png");
                lbllocalIP.Text = _ClientSocket.LocalEndPoint.ToString();
                isConnected = true;
                //this.WindowState = FormWindowState.Minimized;

            });

        }
        catch (SocketException ex)
        {
            isConnected = false;
        }
        finally
        {
            if (isConnected == false)
            {
                counter = 0;
                timer1.Start();
            }
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        isConnected = false;
        counter += 1;
        if (counter > 45)
        {
            counter = 0;
            timer1.Stop();
            AutoStart();
        }
    }

    public void AutoStart()
    {
        if (btnConnect.Text == "Connect")
        {
            if (IsRunning == false)
            {
                _buffer = new byte[8192];
                _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _ClientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(txtServerIP.Text), 9192), new AsyncCallback(connectCallback), null);
            }

        }
        else if (btnConnect.Text == "Disconnect")
        {
            if (IsRunning == true)
            {
                CloseClient();

                btnConnect.Text = "Connect";
                lbllocalIP.Text = "None";
                tslStatus.Text = "Disconnected";
                tslStatus.Image = Image.FromFile(Global.path + @"\image\status\offline.png");

            }

        }
    }

计时器应该在timer1.Start()方法的finally块中引发connectCallback事件后启动。

当我使用断点检查时,在调用timer1.Start()之后,它将更改为Enabled = true状态。

我从工具箱中取出了计时器控制,并将其间隔设置为1000。

但仍然没有timer1.Tick事件发生。

条件:当服务器当时没有运行时,SocketException将会激活,同时我需要启动计时器,这样它会在45秒后尝试再次连接到服务器,如果失败,它将被重新排队。

1 个答案:

答案 0 :(得分:0)

在致电timer1.start()之前,您需要附加事件处理程序。我认为你的代码中缺少它 -

timer1.Tick += new EventHandler(timer1_Tick);

我建议你在构造函数中执行此操作。

此外,您在timer1.start()时致电isConnected == false。我认为您需要将timer1.start()移到if条件之外。

看看这是否有帮助。