簡體   English   中英

如何在C#中的執行任務之間添加暫停

[英]How to add a pause between executing tasks in C#

我當前正在編寫一個程序,要求我在執行任務之間暫停。

所以我有四件事。

  1. 讀取限制
  2. 每次讀取之間的延遲
  3. 總讀取
  4. 全局延遲(在任務完成后將程序暫停'x'秒)

基本上,一項任務被視為“讀取限制”。 因此,例如,如果我有以下設置:

  1. 讀取限制(10)
  2. 每次讀取之間的延遲(20)
  3. 總讀取(100)
  4. 全球延遲(30)

該程序必須基於“讀取限制”從文件中讀取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++;
    }
}

這可能很有趣-這是使用Microsoft的Reactive Framework(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.Sleep描述的示例:

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);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM