Tom Gringauz
Tom Gringauz

Reputation: 811

System.Threading.Thread.Sleep() freezes my code when clicking on a line

I created a method for writing a text slowly for a game. The problem is, when the method is running and I select something with mouse in cmd window, the whole program freezes and when I press escape it continues. Is there something I can do so it won't happen? Can I use something different than System.Threading.Thread.Sleep() for my program to wait?

static void slowly(string sen)
{
    for (int j=0; j<sen.Length-1; j++)
    {
        Console.Write(sen[j]);
        System.Threading.Thread.Sleep(100);
    }
    Console.WriteLine(sen[sen.Length-1]);
    System.Threading.Thread.Sleep(100);
}

Upvotes: 1

Views: 1235

Answers (2)

JasonS
JasonS

Reputation: 7733

The problem is that your sleep code is running on the "Main Thread" of your application. This means that your application can't really do anything else while it's in the .slowly() method.

You need to do something like what @vidstige shows, which is to have your .slowly() method run in another (helper) thread.

A more modern approach would be to:

        static async Task slowly(string sen)
    {
        await Task.Run(() =>
        {
            for (int j = 0; j < sen.Length - 1; j++)
            {
                Console.Write(sen[j]);
                System.Threading.Thread.Sleep(100);
            }
            Console.WriteLine(sen[sen.Length - 1]);
            System.Threading.Thread.Sleep(100);
        });
    }

    public static void Main(string[] args)
    {

        var slowlyTask = slowly("hello world");

        //do stuff while writing to the screen
        var i = 0;
        i++;

        //wait for text to finish writing before doing somethign else
        slowlyTask.Wait();

        //do another something after it's done;
        var newSlowlyTask = slowly("goodbye");
        newSlowlyTask.Wait();
    }

PS: The amount of negative responses to this question is disappointing :(

Upvotes: 2

vidstige
vidstige

Reputation: 13085

    static void slowly(string sen)
    {
        var thread = new System.Threading.Thread(() => {
            for (int j=0; j<sen.Length-1; j++)
            {
                System.Console.Write(sen[j]);
                System.Threading.Thread.Sleep(100);
            }
            System.Console.Write(sen[sen.Length-1]);
            System.Threading.Thread.Sleep(100);
        });
        thread.Start();
    }

Upvotes: 0

Related Questions