我有一个Windows服务,我正在使用Threadpool.QueueUserWorkItem。该服务连接到多个客户端数据库,获取数据,转换为XLS并将文件发送到相应的FTP。如何在Windows服务中使用Threadpool.QueueUserWorkItem?
我有3个有关代码如下问题:
- 我是正确使用Threadpool.QueueUserWorkItem?
- 我是否需要在代码中的任何位置使用Lock以避免出现问题?如果是的话,哪里和什么对象。
- 代码中是否有任何不正确的内容?如果是的话,该如何处理呢?
代码:
private static System.Timers.Timer aTimer = new System.Timers.Timer(50000);
public void OnStart(string[] args)
{
CLE.WriteToEventLog("Service Started");
try
{
aTimer.Elapsed += new ElapsedEventHandler(PerformTimerOperation);
aTimer.Enabled = true;
}
catch (Exception ex)
{
CLE.WriteToEventLog("Error Starting Service: " + ex.Message);
}
}
private void PerformTimerOperation(object source, ElapsedEventArgs e)
{
CLE.WriteToEventLog("Timer Operation Started");
Clients objClient = new Clients();
List<Clients> objClientList = Clients.GetClientList();
foreach (var list in objClientList)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(SendFilesToClient), list);
}
}
private void SendFilesToClient(Object stateInfo)
{
CLE.WriteToEventLog("Send Files To Client Started");
Clients oClient = (Clients)stateInfo;
CLE.WriteToEventLog("Start Proecessing Client: " + oClient.ClientName + ", ClientId: " + oClient.ClientId);
connectionString = App.Database.PrimaryConnectionString(oClient.ClientId);
string reports = oClient.Reports;
string[] values = reports.Split(',').Select(sValue => sValue.Trim()).ToArray();
foreach (string item in values)
{
//Send data to FTP based on cliend id
}
// At this point all reports are being sent to the FTP. We will update the database with LastExecutionDateTime + 1 hour. This will be used as DateFrom param for all reports for the next execution.
}
服务工作正常,我也得到相应的结果,但我需要确保我这样做是正确的,不以对问题以后运行。
刚刚做了@格雷。这是C#.NET 4.0 – Learner 2013-02-26 17:48:17
这对我来说很好。关于你的问题#2,因为你的线程完全独立运行,所以不需要锁定。当您协调对共享资源的访问时,锁定是必要的,但在这种情况下,每个工作线程都有自己的数据库连接,并且正在使用一组不同的“东西”。 – GalacticCowboy 2013-02-26 18:08:31
谢谢@GalacticCowboy! – Learner 2013-02-26 19:40:02