[英]Timer in winform with an iteration
foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
{
makeSelfMoves = replay[item.Key];
codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
PrintPieces(codeFile.PieceState());
// MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a);
}
我想以1秒鍾的間隔執行整個游戲迭代,我負責游戲重播。 我在表單中放置了一個計時器並將其設置為1秒(這應該使棋子每隔1秒移動一次)。 我創建了一個事件,在循環之前我放置了timer1.enabled = true語句。 迭代將快速結束。.您如何使用計時器將迭代設置為使用計時器每秒執行一次?
public void ReplayGame()
{
Class2.replayIsOn = true;
replay=serializeMeh.giveBackDictionary();
int[] makeSelfMoves=new int[4];
//Timer t = new Timer();
//t.Interval = 1000;
//t.Tick += timer1_Tick;
//t.Enabled = true;
//t.Start();
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
//foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
//{
// makeSelfMoves = replay[item.Key];
// codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
// PrintPieces(codeFile.PieceState());
// MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] );
//}
}
如果我想重播,可以激活上述方法。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int[] makeSelfMoves = new int[4];
foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
{
makeSelfMoves = replay[item.Key];// delivers an array of a single move location startrow,startcolumn,endrow,endcolun
codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
PrintPieces(codeFile.PieceState());// prints the code on the board
System.Threading.Thread.Sleep(1000);
}
}
它可以完成工作,但是我遇到的問題是循環完成后,存在的部分消失了。 是否是由於后台工作人員造成的,如果沒有后台工作人員,我在流程結束時不會消失。 我第二次激活該方法,它發生了
在后台線程中運行它,並將Thread.Sleep(1000)放入循環中。
這樣,它將是基於時間的,不會凍結您的應用程序。
我們需要查看您的更多代碼,但這非常簡單:
使用System.Windows.Forms;
SomeMethod(...)
{
Timer t = new Timer();
t.Interval = 1000;
t.Tick += t_Tick;
t.Enabled = true;
t.Start();
}
void t_Tick(...)
{
foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
{
makeSelfMoves = replay[item.Key];
codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
PrintPieces(codeFile.PieceState());
// MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a);
}
}
就個人而言,我會將其放入單獨的線程中並使用Thread.sleep()。 結合訪問GUI元素,我建議改用BackgroundWorker(請參閱MSDN,易於實現)。
如果您堅持使用計時器,我建議您使用“ Ed S.”的建議。 計時器也可以放在您的窗體上,而不是用代碼創建它。 正是您喜歡的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.