Example #1
0
        /// <summary>
        /// Alguns servidores não derrubam a conexão do Mysql após o close e Dispose. Para isso serve essa função.
        /// </summary>
        /// <param name="iMinSecondsToExpire"></param>
        /// <returns></returns>
        public int KillSleepingConnections(int iMinSecondsToExpire)
        {
            string strSQL = "show processlist";

            System.Collections.ArrayList m_ProcessesToKill = new System.Collections.ArrayList();

            string connectionString = System.Web.HttpContext.Current.Items[this.key_conn + "connectionstring"].ToString();

            MySqlConnection myConn   = new MySqlConnection(connectionString);
            MySqlCommand    myCmd    = new MySqlCommand(strSQL, myConn);
            MySqlDataReader MyReader = null;

            try
            {
                myConn.Open();

                // Get a list of processes to kill.
                MyReader = myCmd.ExecuteReader();
                while (MyReader.Read())
                {
                    // Find all processes sleeping with a timeout value higher than our threshold.
                    int    iPID     = Convert.ToInt32(MyReader["Id"].ToString());
                    string strState = MyReader["Command"].ToString();
                    int    iTime    = Convert.ToInt32(MyReader["Time"].ToString());

                    if (strState == "Sleep" && iTime >= iMinSecondsToExpire && iPID > 0)
                    {
                        // This connection is sitting around doing nothing. Kill it.
                        m_ProcessesToKill.Add(iPID);
                    }
                }

                MyReader.Close();

                foreach (int aPID in m_ProcessesToKill)
                {
                    strSQL            = "kill " + aPID;
                    myCmd.CommandText = strSQL;
                    myCmd.ExecuteNonQuery();
                }
            }
            catch (Exception excep)
            {
            }
            finally
            {
                if (MyReader != null && !MyReader.IsClosed)
                {
                    MyReader.Close();
                    MyReader.Dispose();
                }

                if (myConn != null && myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                    myConn.Dispose();
                }
            }

            return(m_ProcessesToKill.Count);
        }