-1

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?

Mugna
  • 59
  • 1
  • 8
  • 2
    http://stackoverflow.com/a/3257751/961113 – Habib Mar 27 '14 at 18:30
  • 1
    This may be a great educational question for learning the threading model, but for production, I would highly recommend using the [Task Parallel Library](http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx). – Erik Philips Mar 27 '14 at 18:34
  • possible duplicate of [Thread.Sleep(0) : What is the normal behavior?](http://stackoverflow.com/questions/3257708/thread-sleep0-what-is-the-normal-behavior) – Chris Ballard Mar 27 '14 at 18:35

3 Answers3

0

If you want to force a context switch, you should give low priority to your Thread / use Thread.Sleep(1), also you can read more on this on the similar question: Thread.Sleep(0) : What is the normal behavior?

Community
  • 1
  • 1
Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
0

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.

sevensevens
  • 1,703
  • 16
  • 27
-1

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

See this - have good answers

Community
  • 1
  • 1
Mzf
  • 5,210
  • 2
  • 24
  • 37