Threadpool.QueueUserWorkItemを使用しているWindowsサービスがあります。このサービスは、複数のクライアントデータベースに接続し、データを取得し、XLSに変換して、対応するFTPにファイルを送信します。
以下のコードに関して3つの質問があります。
- Threadpool.QueueUserWorkItemを正しく使用していますか?
- 問題を回避するために、コードのどこかでロックを使用する必要がありますか?はいの場合、どこでどのオブジェクトに。
- コードに正しくないものはありますか?はいの場合、それをどのように、どのように処理しますか?
コード:
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.
}
サービスは正常に機能し、適切な結果が得られますが、正しく実行していることを確認し、後で問題が発生しないようにする必要があります。