如何避免If/Then语句检查其“;如果“;
本文关键字:如果 检查 语句 何避免 If Then | 更新日期: 2023-09-27 18:19:46
我想知道是否有人知道如何避免在以下代码中重新运行if语句
int x = 1;
load_page(standurl, 0);
firstentryOnload = UrlList[0];
for (int i = 1; i <= lastPage; i++)
{
if (UrlList.Count > setting_EPP) table_populate(0);
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (x > 10)
{
//refresh firstpage,check for new data
System.Threading.Thread.Sleep(delay);
x = 1;
}
x++;
}
我想运行table_populate(0);当UrlList.Count>设置_EPP时
没有"如果/然后"检查每个循环。
本质上,我希望它运行一次If语句,然后停止存在。
我知道如何阻止if/then语句运行,但我不希望它在运行后继续检查
编辑:循环在后台运行,目前需要大约4个小时才能运行完成。我一直在想办法把这件事排除在外,但我运气不太好。我唯一能想到的就是在运行上面代码的线程旁边运行另一个线程,每隔几分钟运行一次If语句?
您可以将条件包装在委托中,并在满足条件时替换委托:
Action check;
check = ()=> {
if (UrlList.Count > setting_EPP)
{
table_populate(0);
check = () => {}; // replace check with no-op.
}
};
....
for(...)
{
check();
...
}
此代码由经过培训的专业人员在封闭课程中编写,不要在家尝试(或任何非自学代码)。:)
更传统的模式——有一个标志,上面写着"满足条件,不再检查"——但实际上它需要if
语句。
注意:如果此代码检查共享日期,则需要使用lock
或其他同步方法(即并发集合之一)。
我首先要注意的是,条件表达式的两边似乎都不受循环主体的影响;即UrlList.Count
和setting_EPP
在循环的主体期间似乎都没有改变。load_page()
或table_populate()
函数可能会更改某些内容,或者另一个线程更改了某些内容,但目前我认为这是真的,因为这个问题在其他方面似乎没有多大意义(我保证:条件检查是NOT,这是性能的一个重要或可衡量的因素)。
鉴于此,这个问题仍然不清楚,但我认为有两种可能性。一种是,您只需要在循环开始时加载表。这很容易;只需在进入循环体之前调用它:
int x = 1;
load_page(standurl, 0);
firstentryOnload = UrlList[0];
if (UrlList.Count > setting_EPP) table_populate(0);
for (int i = 1; i <= lastPage; i++)
{
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (x > 10)
{
//refresh firstpage,check for new data
System.Threading.Thread.Sleep(delay);
x = 1;
}
x++;
}
另一种可能性是,如果条件满足,您希望在每次迭代中都运行此操作,但只希望避免反复检查条件。在这种情况下,您可以将整个内容封装在一个if()
块中:
int x = 1;
load_page(standurl, 0);
firstentryOnload = UrlList[0];
if (UrlList.Count > setting_EPP)
{
for (int i = 1; i <= lastPage; i++)
{
table_populate(0);
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (x > 10)
{
//refresh firstpage,check for new data
System.Threading.Thread.Sleep(delay);
x = 1;
}
x++;
}
}
else
{
for (int i = 1; i <= lastPage; i++)
{
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (x > 10)
{
//refresh firstpage,check for new data
System.Threading.Thread.Sleep(delay);
x = 1;
}
x++;
}
}
当然,您可以将大部分重复的代码抽象到一个单独的方法中。
事实上,还有第三种可能性。我可能错了,在循环过程中UrlList
或setting_EPP
发生了变化,您只想在条件第一次变为true时运行它,而不需要在每次迭代中进行检查。在这种情况下,你可以这样做:
int i = 1;
while (i <= lastPage && UrlList.Count <= setting_EPP)
{
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (i % 10 == 0) System.Threading.Thread.Sleep(delay);
i++;
}
if (i <= lastPage && UrlList.Count > setting_EPP) table_populate(0);
while (i <= lastPage)
{
System.Threading.Thread.Sleep(delay);
load_page(standurl, i);
if (i % 10 == 0) System.Threading.Thread.Sleep(delay);
i++;
}