我有一個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