我有一個間隔爲1秒的計時器。我每秒都會調用這個函數來檢查操作系統的最後輸入時間。如果函數返回的時間超過600(10分鐘),我會調用另一個函數將內容寫入數據庫。函數寫入數據庫時,它不應該
問題出現在這裏,而不是插入一行到數據庫中,該函數將在同一秒內創建許多記錄。我不知道爲什麼會發生這種情況。調試時不會發生這種情況。
public void elapsedGetIdleCount(object source, ElapsedEventArgs e)
{
uint result = GetLastInputTime();
if (result >= 600)
{
result = 0;
tmrIdle.Stop();
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"C:/Users/" + Environment.UserName + "/AppData/Roaming/3CXPhone for Windows/3CXPhone.xml");
var element = xDoc.SelectSingleNode("Accounts/Profiles/Profile/AuthUser");
var extension = element.InnerText.ToString();
SetQueueStatus("LoggedOUT", "Inactivity");
DialogResult mb = MessageBox.Show("You have been Logged Out of the Queues due to inactivity!", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
if (mb == DialogResult.OK)
{
ChangeQueueStatusColor();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void SetQueueStatus(string status, string eventDesc)
{
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"C:/Users/" + Environment.UserName + "/AppData/Roaming/3CXPhone for Windows/3CXPhone.xml");
var element = xDoc.SelectSingleNode("Accounts/Profiles/Profile/AuthUser");
var extension = element.InnerText.ToString();
string conString = "Data Source = lewcomp1\\COMPLIANCE; Initial Catalog = ComplianceData; Integrated Security = True";
using (SqlConnection myCon = new SqlConnection(conString))
{
using (SqlCommand myCMD = new SqlCommand())
{
myCMD.Connection = myCon;
myCMD.CommandText = "UPDATE eData SET QueueStatus = '" + status + "', Extension = '" + extension + "' WHERE UserName LIKE '" + lblUserName.Text + "';";
SqlDataReader myReader;
myCon.Open();
myReader = myCMD.ExecuteReader();
myReader.Read();
myCon.Close();
myCMD.CommandText = "INSERT INTO eQueueData (Date_Time, UserName, Extension, EventID, EventDesc) VALUES ('" + DateTime.Now + "','" + lblUserName.Text + "','" + extension + "','" + status + "','" + eventDesc + "');";
myCon.Open();
myReader = myCMD.ExecuteReader();
myReader.Read();
myCon.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
static uint GetLastInputTime()
{
uint idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
uint envTicks = (uint)Environment.TickCount;
if (GetLastInputInfo(ref lastInputInfo))
{
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime/1000) : 0);
}
最好的辦法是進行調試,把一個破發點上插入到數據庫並看看它是否被調用3次。你的函數可能會在不同的線程上調用。 –
只是可能性:你是否訂閱過3次定時器事件? – 2016-07-15 13:53:05
謝謝你們,我現在回家後會進行調試。不,我只將計時器連接到事件一次。 –