关于管理连接池的,不知道怎么弄。谁能给个代码学习下么?

解决方案 »

  1.   


    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;namespace SmartRead.Data
    {
        public class PooledConnection {
            private SqlConnection _Conn;
            private Guid _ID;
            private bool _Free = true;        public PooledConnection(SqlConnection cnn,Guid id) {
                _Conn = cnn;
                _ID = id;
            }        public Guid ID {
                get { return _ID; }
            }
            public SqlConnection Connection {
                get { return _Conn; }
            }
            public bool Free {
                get { return _Free; }
                set { _Free = value; }
            }
        }    public static class SqlConnectionPool {
            private static Hashtable _Pool=new Hashtable();        public static string _ConnectionString = (string)System.Configuration.ConfigurationManager.AppSettings["连接字符串"];//"Server=.;DataBase=eip;Uid=eip;Pwd=eip;Persist Security Info=True;";        public static PooledConnection RequestConnection() {
                if (_Pool.Count < 1) {
                    SqlConnection cnn = new SqlConnection(_ConnectionString);
                    cnn.Open();
                    PooledConnection pc = new PooledConnection(cnn, Guid.NewGuid());
                    _Pool.Add(pc.ID, pc);
                    pc.Free = false;
                    return pc;
                } else {
                    try {
                        lock (_Pool) {
                            foreach (PooledConnection pc in _Pool.Values) {
                                if (pc.Free) {
                                    pc.Free = false;
                                    return pc;
                                }
                            }
                        }
                    } catch { return null; }
                    SqlConnection cnn1 = new SqlConnection(_ConnectionString);
                    cnn1.Open();
                    PooledConnection pc1 = new PooledConnection(cnn1, Guid.NewGuid());
                    _Pool.Add(pc1.ID, pc1);
                    pc1.Free = false;
                    return pc1;
                }
            }
            public static void ReturnConnection(PooledConnection pc) {
                if (pc.Connection.State == ConnectionState.Executing) {
                    pc.Connection.Close();
                    pc.Connection.Open();
                }
                pc.Free = true;
            }
        }
    }