C#中线程的应用,循环查找某个表是否有记录
这个例子只作了一个线程,是用服务作的,也可以用到控制台程序里...
这里只是提供个思路,如果要实际用到项目中,请了解线程的更多知识.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
//using System.IO;
namespace EAEWS
{
public class Service1 : System.ServiceProcess.ServiceBase
{
private Thread MainThread;
///
/// 必需的设计器变量。
///
private System.ComponentModel.Container components = null;
public Service1()
{
// 该调用是 Windows.Forms 组件设计器所必需的。
InitializeComponent();
// TODO: 在 InitComponent 调用后添加任何初始化
MainThread=new Thread(new ThreadStart(ThreadFunc));
MainThread.Priority=ThreadPriority.Lowest;
}
// 进程的主入口点
static void Main()
{
//System.ServiceProcess.ServiceBase[] ServicesToRun;
// 同一进程中可以运行多个用户服务。若要将
//另一个服务添加到此进程,请更改下行
// 以创建另一个服务对象。例如,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
//
//ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
//System.ServiceProcess.ServiceBase.Run(ServicesToRun);
System.ServiceProcess.ServiceBase.Run(new Service1());
}
///
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
///
private void InitializeComponent()
{
// components = new System.ComponentModel.Container();
// this.ServiceName = "myEAEWS";
this.ServiceName = "myEAEWS";
}
///
/// 清理所有正在使用的资源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
///
/// 设置具体的操作,以便服务可以执行它的工作。
///
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
MainThread.Start();
myCh.Common.SystemFramework.SystemFramework.ConnectionString ="Data Source=192.168.0.1;Initial Catalog=datatable;User Id=sa;Password=;";
myCh.Common.SystemFramework.SystemFramework.ConnectionType = "Sqlserver";
}
///
/// 停止此服务。
///
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
MainThread.Abort();
}
public static void ThreadFunc()
{
// int j = 0;
while(true)
{
try
{
System.Threading.Thread.Sleep(1000); //1秒钟处理一次所有记录
EAE.EnterAndExitLogic.MsgTinterfaceData.MsgTinterfaceData myMsgCount = new EAE.EnterAndExitLogic.MsgTinterfaceData.MsgTinterfaceData();
int iCount = myMsgCount.MsgList().Rows.Count;
//如果一条也没有
if(iCount >0)
{
for(int i=1 ;i <= iCount;i++)
{
EAE.EnterAndExitLogic.MsgTinterfaceData.MsgTinterfaceData myMsg = new EAE.EnterAndExitLogic.MsgTinterfaceData.MsgTinterfaceData();
myMsg.main();
}
}
}
catch
{}
}
}
}
}