我正在使用一個Windows服務的調用API,得到響應和更新Sql表它工作正常,但有一段時間它是Hit API兩次。我無法理解。這裏是我的代碼Windows服務Hit API多次有時
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(15000D);
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.proccessQue();
}
,這裏是proccessQue()方法
//SELECT record form table
SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM TABLE_NAME WHERE is_done=0 AND date>DATEADD(minute,-5,GETDATE())", conn);
DataTable dt = new DataTable();
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
string parameters= dt.Rows[i]["parameters"] + "";
string api = "http://domain.com/page.aspx?parameters=" + parameters;
HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(api);
HttpWebResponse httpres = (HttpWebResponse)httpreq.GetResponse();
StreamReader sr = new StreamReader(httpres.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
if (results.Contains("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"))
{
try
{
string response= "";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(results);
var res2 = xmlDoc.SelectNodes("RechargeRequest/RequestResponse/APIRef");
if (res2 != null)
response= res2[0].InnerText;
SqlCommand cmd = new SqlCommand("UPDATE TABLE_NAME SET field='" + response+ "',is_done=1 WHERE id=" + rId, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
}
}
請幫我在哪裏,我錯了。
多種事情1.您的API調用處於記錄循環中。所以會根據你的循環結果命中0-n次。這可能是您的查詢返回多個方法。 2.是否有可能你的processQueue方法比定時器的每一個已經發生的事件花費更長的時間?我的建議是1。檢查查詢的結果,因爲它可能會返回多於一條記錄2.停止計時器在已過的事件中處理隊列,然後重新啓動它。最後,鑑於這是2017年,您最好使用異步/等待模式,並使用更強大的HttpClient類來處理Web請求。 – Nico
哦,最後你有很多IDisposable的不配置 – Nico
是的,它可能是查詢返回多於1行。如何在經過的事件中停止計時器處理隊列,然後重新啓動它?請幫幫我。我正在使用此服務進行充值網站,因此無法延長充電時間後計時器的使用時間。 –