简体   繁体   中英

Trouble with Thread.Sleep(0)

I tried to test the context switch using Thread.Sleep(0) using this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadMethod
{
    class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadProc: {0}", i);

                Thread.Sleep(0);
            }
        }
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(ThreadMethod));

            t.Start();

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Main Thread here!");

                Thread.Sleep(0);
            }



            t.Join();
        }
    }
}

but result was the following:

Main Thread here!
ThreadProc: 0
ThreadProc: 1
ThreadProc: 2
ThreadProc: 3
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
Main Thread here!
ThreadProc: 9

I am developing on Surface PRO 2. Is this behaviour due to a multicore system?

如果你想强制上下文切换,你应该给你的线程低优先级/使用Thread.Sleep(1) ,你也可以在类似的问题上阅读更多关于这个的内容: Thread.Sleep(0) : What is the normal behavior ?

I think what you're looking for is Thread.Yield . This will signal OS that the current thread doesn't need the CPU time anymore and will make the OS switch to another thread if one is waiting.

if you want context switch, try Thread.Sleep() with something other than Zero.

See this - have good answers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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