N.D
N.D

Reputation: 1049

Thread.Sleep c#.NET

I want to put a thread to sleep, and I don't have a sleep method.

I have using System.Threading.

In my code i write :

Thread t = new Thread(StartPointMethod);
t.

In the Methods list there is no Sleep....

What could be the problem?

Upvotes: 5

Views: 52965

Answers (8)

Fre T.
Fre T.

Reputation: 1

The System.Thread has a function specifically made for that.

System.Threading.Thread.Sleep(100)

The Sleep function takes one argument in milliseconds.

Upvotes: -3

MKK
MKK

Reputation: 9

Thread.Sleep(milliseconds) lets the current thread sleep for x number of milliseconds. There is no way for a thread to put another thread to sleep. Thread.Sleep always refers to current thread.

Upvotes: -2

Nikki Locke
Nikki Locke

Reputation: 146

Just to expand a little on the (correct) answers above, Thread.sleep is a static method. Static methods are associated with a class (Thread), but not a particular instance of the class.

So, to call Thread.Sleep - you just write (as has been said above) "Thread.Sleep(msecs)" - you don't need to create a thread to call the method.

Upvotes: 2

Saleh
Saleh

Reputation: 3032

This code for sleep current thread for 20 second.

System.Threading.Thread.Sleep(20000);

Upvotes: 21

Jim Mischel
Jim Mischel

Reputation: 134125

There's no way for thread A to tell thread B to sleep. That is, you can't write:

Thread t = new Thread(...);
t.Start();
t.Sleep();

You can suspend a thread, and then resume it later, but this is a very bad idea. Doing so risks all kinds of potentially disastrous consequences. There's a reason that Thread.Suspend has been obsoleted.

In normal code (i.e. outside writing debuggers and OS-level stuff), there's never a good reason to suspend a thread. And there's almost never a good reason to call Thread.Sleep. If you find that you need to suspend or sleep a thread, there's almost certainly a design problem that you need to address.

Upvotes: 4

Asfour
Asfour

Reputation: 124

you have to use this code :

Thread.Sleep(5);

Upvotes: 2

faester
faester

Reputation: 15086

Sleep is a static method on 'Thread', not an instance method. So the way to make you Thread sleep is to have a Thread.Sleep statement inside it executing method.

Since Thread.Sleep will always make the executing thread sleep, you can do something in the line of the example below.

    private void Foo()
    {
        Thread t = new Thread(new ThreadStart(ThreadWorker));
        t.Start();

        t.Join();
    }

    private void ThreadWorker()
    {
        Console.WriteLine("Prior to sleep");
        Thread.Sleep(100);
        Console.WriteLine("After sleep sleep");
    }

Upvotes: 10

Farzin Zaker
Farzin Zaker

Reputation: 3606

Use this method in any method in your new thread that you want to sleep.

System.Threading.Thread.Sleep(500);

Upvotes: 12

Related Questions