سؤال

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
هل كانت مفيدة؟

المحلول

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top