//声明thread数组
Thread[] threads;
//自定义线程数
int threadcount=3
//ThreadStart 委托 被委托对象为线程过程
ThreadStart startAnylisis = new ThreadStart(anlysis);
//初始化多线程数组
threads = new Thread[threadcount];
//初始数组中各线程,同时开启线程
for (int i = 0; i < threadcount; i++)
{
threads[i] = new Thread(startAnylisis);
threads[i].Start();
}
/// <summary>
/// 线程过程,实例或静态均可
/// </summary>
private void anlysis()
{
...线程过程主体内容,自行编码
//线程执行完闭,关闭线程组
threadClose();
}
/// <summary>
/// 关闭线程组的线程
/// </summary>
private void threadClose()
{
for (int i = 0; i < threadcount; i++)
{
threads[i].Abort();
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
上面是同事的,下面是我写的
static void Main(string[] args)
{
string dt = System.DateTime.Now.ToString();
//定义线程对象
MyTask task1 = new MyTask("1");
//MyTask task2 = new MyTask("2");
//打开线程
task1.m_thread.Start();
//task2.m_thread.Start();
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
//垃圾回收
GC.KeepAlive(task1.timer);
}
public class MyTask
{
//线程对象
public Thread m_thread;
//线程编号
string _threadNO;
//定时对象
public Timer timer;
public MyTask(string threadNO)
{
//设置线程编号
_threadNO = threadNO;
//初始化线程
m_thread = new Thread(new ThreadStart(TimerTabState));
}
public void TimerTabState()
{
//设置定时触发的方法名称
TimerCallback timerDelegate = new TimerCallback(DataImport);
//设置时间间隔 每十分钟触发一次DataImport方法
timer = new Timer(timerDelegate, _threadNO, 1000, 600000);
}
public void DataImport(object obj)
{
StringBuilder sql = new StringBuilder();
//线程编号,用于区分多线程场合
string threadNO = obj.ToString();
//Web端连接
string strWebCnn = @"Sqlserver数据库连接字符串";
SqlConnection sqlWebCnn = new SqlConnection(strWebCnn);
sqlWebCnn.Open();
//查询当日订购手机号码
sql.Append("数据库查询语句 ");
SqlCommand cmd = new SqlCommand();
DataSet dsWeb = new DataSet();
SqlDataAdapter sqlDa = new SqlDataAdapter(sql.ToString(), sqlWebCnn);
//清空DataSet对象
dsWeb.Clear();
//查询结果填充到DataSet对象中
sqlDa.Fill(dsWeb);
//将查询结果导出Xml
//dsWeb.WriteXml("D://reg_sms_user_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml");
//创建日志文件
StreamWriter strWrit = new StreamWriter("D://UpdLog_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt");
//服务器端连接
string strSerCnn = @"Sqlserver数据库连接字符串";
SqlConnection sqlSerCnn = new SqlConnection(strSerCnn);
sqlSerCnn.Open();
cmd.Connection = sqlSerCnn;
DataSet dsSer = new DataSet();
try
{
//处理逻辑
{
//控制台输出
Console.WriteLine("Thread " + threadNO + " " + System.DateTime.Now.ToString() + ":" + "Update Data Nothing");
//写入日志
strWrit.WriteLine(System.DateTime.Now.ToString() + " Update Data Nothing");
}
}
catch (Exception ex)
{
//控制台输出
Console.WriteLine("Error :" + ex.ToString());
//写入日志
strWrit.WriteLine(System.DateTime.Now.ToString() + "Error :" + ex.ToString());
}
finally
{
sqlSerCnn.Close();
sqlWebCnn.Close();
dsSer.Dispose();
dsWeb.Dispose();
cmd.Dispose();
sqlDa.Dispose();
strWrit.Close();
}
}
}