我目前正在编写一个程序,要求我在执行任务之间暂停。
所以我有4件事。
基本上,一项任务被视为“读限制”。所以,例如,如果我有这些设置:
程序必须根据“读取限制”从文件中读取10行,并且在读取每行之间,根据“每次读取之间的延迟”,有20秒的延迟。在读取10行后,根据“全局延迟”暂停30秒。当全局延迟结束时,它会在停止的地方再次启动并继续执行此操作,直到达到基于“总读数”的限制为100。
我尝试使用System.Threading.Thread.Sleep()
,但我无法使用它。我怎样才能用C#实现这个目标?
提前致谢。
//用我的一些代码更新。
我像这样加载文件:
private void btnLoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] lines = System.IO.File.ReadAllLines(ofd.FileName);
}
}
我有4个全局变量:
public int readLimit = 0;
public int delayBetweenRead = 0;
public int totalReads = 0;
public int globalDelay = 0;
public int linesRead = 0;
我想制作这样的功能:
private void doTask()
{
while (linesRead <= readLimit)
{
readLine(); // read one line
doDelay(); // delay between each line
readLine(); // read another line and so on, until readLimit or totalReads is reached
globalDelay(); // after readLimit is reached, call globalDelay to wait
linesRead++;
}
}
答案 0 :(得分:4)
这可能是有趣的 - 这是使用Microsoft的Reactive Framework(NuGet&#34; Rx-Main&#34;)实现此目的的方法。
int readLimit = 10;
int delayBetweenRead = 20;
int globalDelay = 30;
int linesRead = 100;
var subscription =
Observable
.Generate(0, n => n < linesRead, n => n + 1, n => n,
n => TimeSpan.FromSeconds(n % readLimit == 0 ? globalDelay : delayBetweenRead))
.Zip(System.IO.File.ReadLines(ofd.FileName), (n, line) => line)
.Subscribe(line =>
{
/* do something with each line */
});
如果您需要在自然完成之前停止阅读,请致电subscription.Dispose();
。
答案 1 :(得分:2)
你的意思是
我尝试过使用System.Threading.Thread.Sleep()但是我无法使用它
以下是使用Thread.Sleep实现所描述内容的示例:
+----+-----+------+---------+-----------+
| id | src | dest | time | requests |
+----+-----+------+---------+-----------+
| 6 | abc | xyz | 1100000 | 200200000 |
| 7 | def | uvw | 10 | 300 |
| 8 | abc | uvw | 100 | 5000 |
| 9 | def | xyz | 11000 | 140000 |
+----+-----+------+---------+-----------+