简体   繁体   中英

Re attempt server connection after some time

I have a client which is a windows process to get updates from server in c#. The server may be down for maintainance for some time, the client wont not be able to connect to server at this point if it needs to update.

I want to design so that the client re attempts connection after 30 min if connection attempt fails. I understand Thread.Sleep would be bad idea so I would like some suggestions on how to do it.

Thanks in advance.

Use a timer. If the function fails to connect, then set a timer to call it again...

eg

    class MyClass
    {




 System.Timers.Timer m_ConnectTimer = null;

        ..
        ..

    void ConnecToServer()
    {
        if (m_ConnectTimer != null)
        {
            m_ConnectTimer.Enabled = false;
            m_ConnectTimer.Dispose();
            m_ConnectTimer = null;
        }

        //Try to connect to the server

        if (bConnectedToTheServer)
        {
            //Do the servery stuff
        }
        else //set the timer again
        {
            m_ConnectTimer = new Timer(30 * 60 * 1000);
            m_ConnectTimer.Elapsed += new ElapsedEventHandler(TimerHandler)
            m_ConnectTimer.Enabled = true;
        }

    }


    void TimerHandler(object sender, ElapsedEventArgs e)
    {
        ConnectToServer();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM