我一直在這個項目上工作了3天,直到上午3-4點,我相信我知道它在哪裏搞亂(我的意見是標記計算,我相信是問題),但至於解決計算,如果那甚至會修復我不確定的計時器。我在代碼中標明瞭我認爲是問題的地方,但我會接受他們認爲可以修復它的地方或它搞亂的地方的任何意見。如果它是(檢查)方法中的一個計算,那麼我不確定什麼計算可以修復它。如果別人看到別的東西,我不想告訴我。我看了幾個不同的選項,似乎沒有任何工作。 (y)(秒,分鐘,小時,天)每隔(x)(秒,分鐘,小時,天)發送一條消息。 ()是用戶的輸入。 (x)過後,它的時間到,停止定時器,發送方法,然後重新啓動定時器。 (例如(用戶輸入)每隔(30)秒發送1條消息(2)分鐘)應該發送4輪消息,但由於定時器不停止而提前結束。我知道它在哪裏搞亂了,但有一點指導意見和其他意見會有幫助。定時器沒有停止,然後在執行方法後重新啓動?
<code>
private void TimeKeeperTimerElapsed(object sender, ElapsedEventArgs e)
{
if (flag == true && EndTime > DateTime.Now)
{
_timeKeeper.Stop();
Check();
_timeKeeper.Start();
}
if (flag == true && EndTime < DateTime.Now)
{
TestCompleted();
}
}
bool flag = true;
/// <summary>
/// Method "Check" checks to see it it is time to send a message, time elapsed and time left
/// </summary>
private void Check()
{
if (SelectedPerfTest != null && flag == true)
{
//Est. Date Time Now
var ct = DateTime.Now;
//Time Elapsed Output form now (counts up)
var te = ct.Subtract(StartTime);
TimeElapsed = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", te.Days, te.Hours,
te.Minutes,
te.Seconds);
// Time Left from now output (counts down)
var tl = EndTime.Subtract(ct);
TimeLeft = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", tl.Days, tl.Hours,
tl.Minutes,
tl.Seconds);
//Calculate the time til the next message (counting down)
var nnm = CalculateNextMessage(DateTime.Now);
NextNewMessage = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", nnm.Days, nnm.Hours,
nnm.Minutes,
nnm.Seconds);
//I feel like the Problem is here this equation will call the method to send message but the timer continues to tick... I
//need it to stop when the time elapsed that the user put in ex. user enter (send 1 message every (20 seconds)
//for (2 hours)) it needs to stop in 20 sec. to send message then check if its time to end (if 2 hours are up).
//If not send message in another 20 sec.
if (DateTime.Now.Add(CalculateNextMessage(DateTime.Now)) < DateTime.Now && EndTime > DateTime.Now)
if (ct.Subtract(StartTime) == LastExecuted.AddMilliseconds(ts).Subtract(ct))
{
if (CurrentProduct == ("Babyware"))
{
if (SelectedPerfTest == ("Short Test"))
{
ExecuteShortTest();
}
if (SelectedPerfTest == ("Long Test"))
{
ExecuteLongTest();
}
if (SelectedPerfTest == ("UCN"))
{
ExecuteUCNTest();
}
}
else
if (CurrentProduct == ("Antware"))
{
if (SelectedPerfTest == ("Short Test"))
{
ExecuteGAShortTest();
}
if (SelectedPerfTest == ("Long Test"))
{
ExecuteGALongTest();
}
}
}
}
}
#endregion
</code>
請限制您的代碼示例到相關部分。理想的示例是[簡短,獨立和可編譯](http://sscce.org/)。通讀整個源代碼非常耗時,並且會爲您提供更少的答案。 – 2012-08-13 16:16:43
如果您的'Check'例程引發異常,並且您的計時器類型爲'Threading.Timer',它將繞過'Start()'並且有時不會通知您該異常。也許在'try/finally'中包裝'Check()'並將'Start()'調用移至'finally'塊可能會有幫助。 – 2012-08-13 16:55:04
我確實試過你的建議,但定時器仍然不會停止發送消息。謝謝。 – 2012-08-13 17:27:23