简体   繁体   English

Thread.Sleep为什么不在示例中阻塞线程

[英]Thread.Sleep why not block the thread on example

Thread.Sleep() is putting main thread on hold for certain number of milliseconds. Thread.Sleep()将主线程保持一定的毫秒数。 I would expect Thread.Sleep() to block main thread even if it's called from different thread ( Task.Run() creates new thread in fact), why when it comes to PleaseWait() my loop which is on main thread is still executing since Thread.Sleep was called? 我希望Thread.Sleep()阻塞主线程,即使它是从其他线程中调用的( Task.Run()实际上创建了新线程),为什么当涉及PleaseWait() ,主线程上的循环仍在执行自从Thread.Sleep被调用以来? It should be paused to me. 它应该对我暂停。 Or is it because in fact that Thread.Sleep() called on different thread by Task.Run is now not exactly Thread.Sleep for main thread now but it is referring to the new thread created in Task.Run . 还是因为实际上Task.Run在不同线程上调用的Thread.Sleep()现在不完全是主线程的Thread.Sleep ,而是引用Task.Run创建的新线程。 Means it's not Sleep for main thread but for thread created on Task.Run side ? 意味着对于主线程来说不是休眠,而是在Task.Run端创建的线程不是Sleep? Hope it's clear. 希望清楚。

class Program
    {
        static void Main(string[] args)
        {
            Task.Run(() => PleaseWait());

            var n = 0;
            while (n < 10000)
            {
                Console.WriteLine(n);
                n++;
            }

            Console.ReadLine();
        }


        public static void PleaseWait()
        {
            Thread.Sleep(10000);
            Console.WriteLine("After sleep");
        }
    }

I would expect Thread.Sleep() to block main thread even if it's called from different thread 我希望Thread.Sleep()阻止主线程,即使它是从其他线程调用的也是如此

Lets visit the documentation 让我们访问文档

Thread.Sleep Method Thread.Sleep方法

Suspends the current thread for the specified amount of time. 将当前线程挂起指定的时间。

Meaning it blocks the thread it is called from, Case closed 表示它阻塞了调用它的线程,case关闭

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM