Using a timer to delay a line by line readline method C#

不羁的心 提交于 2021-01-29 17:43:04

问题


I am using C# Windows Forms using Visual Studio 2010. Don't let the Console part confuse you it's a user defined thing not the actual console. So I have a method that prints a file line by line. I have to make it appear to print slowly so I am currently using Thread.Sleep to slow the line by line printing. I cannot use this because it freezes up some other components in the program. I was hoping to see if this could be done with a timer instead. Though all the examples I see being used with a timer generally have a method being called by the timer. Not have a timer delay in the middle of a method. So I'm not sure how I can go about using a timer here.


public void SlowPrint(string FileName)
{

    string line;

    string tempFileName;

    string MyFilesDir = "..\\..\\myFolder\\";

    tempFileName = Path.Combine(MyFilesDir, FileName);

    if (System.IO.File.Exists(tempFileName))
    {
        System.IO.StreamReader file = new System.IO.StreamReader(tempFileName);

        while (((line = file.ReadLine()) != null))
        {
            Console.WriteLine(line);
            System.Threading.Thread.Sleep(700);  //This has to go
        }
        file.Close();
    }
    else
    {
        Console.WriteLine("Error " + tempFileName + " does not exists");
    }
    Console.ReadLine();
}//end SlowPrint method

回答1:


awaiting Task.Delay makes this operation quite easy, in combination with File.ReadLines:

public async Task SlowPrint(string fileName)
{
    //TODO stuff to generate real file path and check if it exists
    foreach(var line in File.ReadLines(fileName))
    {
        Console.WriteLine(line);
        await Task.Delay(700);
    }
}

A pre C# 5.0 solution is harder, but certainly possible. Just create a timer and read a new line whenever it fires:

public void SlowPrint(string FileName)
{
    var iterator = File.ReadLines(FileName).GetEnumerator();
    System.Threading.Timer timer = null;
    timer = new System.Threading.Timer(o =>
    {
        if (iterator.MoveNext())
            Console.WriteLine(iterator.Current);
        else
        {
            iterator.Dispose();
            timer.Dispose();
        }
    }, null, 700, Timeout.Infinite);
}


来源:https://stackoverflow.com/questions/21888775/using-a-timer-to-delay-a-line-by-line-readline-method-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!