简体   繁体   中英

Program hang indefinitely on MySqlConnection.Open() call

I am using MySqlConnection to access a remote database. It works fine on most computers.

However. Now I have a case in which the MySqlConnection.Open() call hangs for ever. I have added some write statements to see where it hangs. See the code below. The statement "_Debug.Write("OpenConnection", "Connection succeeded.");" is never reached. Also no exception is thrown. I have tried to run the application as an administrator but it still hangs here. It must be an environment issue since this works fine on all other computers. (I am using .NET Framework 3.5)

Does anyone has a solution for this? I hope so. Kind regards Rob Baaij ----------------------------------------------------my c# source code private MySqlConnection connection; private string _server = "Server=5.666.82.191;Database=unknown;Uid=me;Pwd=mypasswd";

   public void getUserData()
    {
        using (connection = new MySqlConnection(_server))
        {
            if (OpenConnection())
            {
                getData();

                connection.Close();
            }
        }
    }

     private bool OpenConnection()
    {
        bDatabaseConnectionSucceeded = false;
        try
        {
            _Debug.Write("OpenConnection", "Opening connection now!!");
            connection.Open();
            bDatabaseConnectionSucceeded = true;
            _Debug.Write("OpenConnection", "Connection succeeded.");
            return true;
        }
        catch (MySqlException ex)
        {
            _Debug.Write("OpenConnection", "Connection failed." + ex.Message);
            Debug.WriteLine(ex.Message);
            return false;
        }
    }
  1. You don't need to do connection.close(); This is redundant, since it's created in a using block.

  2. Why wait for the connection to open? Why not spin off a different thread that you wait on in the current thread? If it doesn't respond, you can give up with no worries and try again later.

This is especially useful if you're connecting to a remote server and you lose your internet connection. connnection.open() won't hang indefinitely, but it will hang its owning thread for an undesirable amount of time.

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