如何在c#中添加执行任务之间的暂停
本文关键字:执行任务 之间 暂停 添加 | 更新日期: 2023-09-27 18:09:56
我目前正在编写一个程序,它要求我在执行任务之间有一个暂停。
所以我有4个东西
- 阅读限制
- 每次读取时延 总读
- 全局延迟(任务完成后暂停程序'x'秒)
基本上,一个任务被认为是"读取限制"。例如,如果我有这些设置:
- 读取限制(10)
- 每次读取时延(20)
- 总读取数(100)
- 全局延迟(30)
程序必须根据"读取限制"从文件中读取10行,并且在读取每行之间,根据"每次读取之间的延迟"有20秒的延迟。读取10行后,根据"全局延迟"暂停30秒。当全局延迟结束时,它从停止的地方重新开始,并继续这样做,直到达到基于"Total Reads"的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);
}
}
我有四个全局变量:
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++;
}
}
这可能会让你感兴趣——这是使用微软的响应式框架(NuGet "Rx-Main")的方法。
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();
。
你说
是什么意思?我试过使用System.Threading.Thread.Sleep()但是我不能使它工作
下面是一个使用Thread实现您所描述的功能的示例。睡眠:
using (var fs = new FileStream("C:''test.txt", FileMode.Open, FileAccess.Read))
{
using (var sr = new StreamReader(fs))
{
int nRead = 0;
while (nRead < settings.Total)
{
for (int i = 0; i < settings.ReadLimit && nRead < settings.Total; ++i, nRead++)
{
Console.WriteLine(sr.ReadLine());
if (i + 1 < settings.ReadLimit)
{
Thread.Sleep(settings.Delay * 1000);
}
}
if (nRead < settings.Total)
{
Thread.Sleep(settings.GlobalDelay * 1000);
}
}
}
}