如何在方法循环仍然有效的情况下动态分配值并在表单上进行更新?在我的程序中发生的事情是,它在启动时会挂起,直到它完成(找到数独的解决方案),然后填充文本框。 这是主要方法:
bool SolveSudoku()
{
if (!FindUnassignedLocation()) return true;
for (int num = 1; num <= 9; num++)
{
if (NoConflicts(emptyRow, emptyCol, num))
{
Grid[emptyRow, emptyCol].Text = num.ToString();
Grid[emptyRow, emptyCol].BackColor = Color.White;
Grid[emptyRow, emptyCol].ForeColor = Color.Black;
if (SolveSudoku()) return true;
Grid[emptyRow, emptyCol].Text = "";
}
}
bool checkIfFirstBackTrack = true;
do {
if (checkIfFirstBackTrack)
{
backtrackCounter++;
checkIfFirstBackTrack = false;
}
if (emptyCol == 0 && emptyRow > 0)
{
emptyCol = 8;
emptyRow--;
}
else if (emptyCol > 0)
{
emptyCol--;
}
}
while(Preset[emptyRow, emptyCol] != "");
return false;
}
}
答案 0 :(得分:1)
一个选项是后台工作人员See more information on setting up a background worker here.:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
//// your code here
}
}
}