加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Thread.Sleep(0)和Join()

发布时间:2020-12-15 23:44:07 所属栏目:百科 来源:网络整理
导读:我正在读一本关于多线程程序的书,我发现了这个小例子: public static class Program { public static void ThreadMethod() { for (int i = 0; i 10; i++) { Console.WriteLine(“ThreadProc: {0}”,i); Thread.Sleep(0); } } public static void Main() { T
我正在读一本关于多线程程序的书,我发现了这个小例子:

public static class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(“ThreadProc: {0}”,i);
                Thread.Sleep(0);
            }
        }
        public static void Main()
        {
            Thread t = new Thread(new ThreadStart(ThreadMethod));
            t.Start();
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine(“Main thread: Do some work.”);
                Thread.Sleep(0);
            }
            t.Join();
        }
    }

我有太多问题:

1)Thread.Sleep(0)的用途是什么,我的意思是,我尝试了两种情况:有或没有Thread.Sleep(0),运行时没有太大区别

2)t.Join()在这里真的很有用,因为它在Main方法的最后?

解决方法

Thread.Sleep(0)将屈服于其他线程的优先级低于您的优先级:

If the value of the millisecondsTimeout argument is zero,the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run,execution of the current thread is not suspended.

因此,在这个例子的情况下,尝试使线程以大致相同的速度运行.

Thread.Join的使用表明,在线程完成工作之前,不需要结束程序.但是,正如Scott Chamberlain所指出的那样,默认情况下IsBackground属性为false,因此您的线程是前台线程,并且将保持程序自己运行,直到它们完成工作.如果你的程序有更多事情要做,并且通常有,那需要线程工作的结果,那么Join调用真的很重要.

尝试将IsBackground属性设置为不同的值,并尝试删除Join调用以查看发生的情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读