【发布时间】:2017-08-07 12:56:13
【问题描述】:
我在 C# 中编写了一个代码,我从 Access 数据库中提取了一些记录,但是我需要在进行下一次迭代时依赖于单击按钮。我尝试了一些线程或任务,但它没有工作,因为它阻止了我需要它被看到和点击的 UI。
代码如下:
bool nextClick = false ;
while (readerSelect.Read())
{
// show the correct panel
if (string.Compare(readerSelect[2].ToString(), "P1") == 0)
{
// panel with type 1
textBoxP1Text1.Text = readerSelect[3].ToString();
textBoxP1Text2.Text = readerSelect[4].ToString();
pictureBoxP1Image.ImageLocation = readerSelect[6].ToString();
}
else
{
// panel with type 2
textBoxP1Text2.Text = readerSelect[5].ToString();
}
//this while need to be kind of infinite so the interation can't be processed and
//so when i need to change iteration i click the buttonNext
while (!nextClick) {
startWhile:;
MethodInvoker mi = delegate () {
if (nextClick)
{
Application.DoEvents();
// System.Windows.Forms.Application.Run();
}
};
this.Invoke(mi);
//break;
goto startWhile;
}
private void buttonNext_Click(object sender, EventArgs e)
{
// click on the next button
nextClick = true;
}
【问题讨论】:
-
如果您只需要在单击后转到下一个项目,则不要使用 while 循环...只需在每次单击时执行一个...
-
这将对我们的连接产生重大影响,这有点糟糕,但感谢您的回答
-
“对您的连接产生重大影响”是什么意思?那是不正确的。你现在这样做的方式和这种方式只会读取有多少条记录。你误会了。我建议您阅读 DataReader 文档,直到您更好地理解它作为第一点
-
非常最简单的做法是用
while(!nextClick) {Application.DoEvents();} nextClick = false;替换整个块,它会起作用,但也会导致高 CPU 无所事事的紧密循环。