开发者

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?


This code for sleep current thread for 20 second.

System.Threading.Thread.Sleep(20000);


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

System.Threading.Thread.Sleep(500);


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


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.


you have to use this code :

Thread.Sleep(5);


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.


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.


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

System.Threading.Thread.Sleep(100)

The Sleep function takes one argument in milliseconds.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜