数据库及WebService通过线程控制连接时间管理
时间:2011-03-18 来源:如歌
using System;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace Logic
{
/**/
/// <summary>
/// 连接类型
/// </summary>
public enum DatabaseType
{
SqlServer,
Odbc,
Oracle,
OleDB,
WebService
}
/**/
/// <summary>
/// 通过线程控制数据库及WebService连接时间管理
/// </summary>
public class XngConnConsole
{
private bool bIsConn = false; // 判断连接是否成功
private Thread tdConn; // 连接数据库的线程
private string strConn = null; // 连接字符串
private int nTimeout = 0; // 超时时间
private DatabaseType dbType; // 数据库类型
private IDbConnection iConn = null; // 数据库连接字符串对象接口
private object result = null; //WebService 委托方法返回的结果
public delegate object ConnWebService(object[] args); //WebService 委托类型
private ConnWebService conWebService; //WebService 委托
/**/
/// <summary>
///数据库构造函数
/// </summary>
/// <param name="Conn">连接字符串</param>
/// <param name="timeOut">超时时间(毫秒)</param>
/// <param name="DBType">数据库类型</param>
public XngConnConsole(string Conn, int timeOut, DatabaseType DBType)
{
strConn = Conn;
nTimeout = timeOut;
dbType = DBType;
}
/**/
/// <summary>
/// WebService构造函数
/// </summary>
/// <param name="Conn">连接字符串</param>
/// <param name="timeOut">超时时间(毫秒)</param>
/// <param name="DBType">数据库类型</param>
/// /// <param name="_conWebService">WebService委托</param>
public XngConnConsole(int timeOut, DatabaseType DBType, ConnWebService _conWebService)
{
//strConn = Conn;
nTimeout = timeOut;
dbType = DBType;
conWebService = _conWebService;
}
/**/
/// <summary>
/// 打开数据库或WebService
/// </summary>
/// <param name="args">WebSerivew委托参数</param>
/// <returns>连接对象接口</returns>
public object Open(object[] args)
{
iConn = null;
result = null;
tdConn = new Thread(() => { ConnDatabase(args); });
Thread tdTimeOut = new Thread(new ThreadStart(ConsoleTimeOut));
tdConn.SetApartmentState(ApartmentState.MTA);
tdConn.IsBackground = true;
tdTimeOut.Start();
tdTimeOut.Priority = ThreadPriority.Highest;
tdConn.Start();
tdTimeOut.Join(nTimeout); //连接超时控制线程,不然主线程会直接返回null. !!!!
if (dbType != DatabaseType.WebService)
{
return iConn;
}
else
{
return result;
}
}
/**/
/// <summary>
/// 超时控制
/// </summary>
private void ConsoleTimeOut()
{
Thread.Sleep(nTimeout);
if (bIsConn == false)
{
tdConn.Abort();
tdConn = null;
iConn = null;
}
}
/**/
/// <summary>
/// 连接数据库
/// </summary>
private void ConnDatabase(object[] args)
{
try
{
//根据数据连接类型创建数据访问类
switch (dbType)
{
case DatabaseType.SqlServer:
iConn = new SqlConnection(strConn);
iConn.Open();
break;
case DatabaseType.Odbc:
iConn = new OdbcConnection(strConn);
iConn.Open();
break;
case DatabaseType.OleDB:
iConn = new OleDbConnection(strConn);
iConn.Open();
break;
case DatabaseType.Oracle:
iConn = new OleDbConnection(strConn);
iConn.Open();
break;
case DatabaseType.WebService:
if (conWebService != null)
{
result = conWebService.Invoke(args);
break;
}
else
{
bIsConn = false;
return;
}
}
bIsConn = true;
}
catch (Exception exp)
{
}
}
}
}