maz
maz

Reputation: 523

When a context switch happens will the thread remain on the same number?

I have a question about using of Task.

I write the follow code:

static void Main(string[] args)
{
    Task t = new Task(() => DoWork());
}

private static void DoWork()
{
    //Do Something
}

DoWork is run on thread from ThreadPool. for the example let assume the thread num is 3.

My Question: There is option that in middle of the func DoWork, because of context switch etc', the continuous of the function will be in thread that is not 3?

Thank!

Upvotes: 4

Views: 2120

Answers (2)

Christos
Christos

Reputation: 53958

My Question: There is option that in middle of the func DoWork, because of context switch etc', the continuous of the function will be in thread that is not 3?

No. From the moment a thread from the thread pool would be assigned to run the code of DoWork, this thread would execute the code and when the the thread has completed its work would back to the queues that contains other work that should be run to fetch the next one, if there is any at all.

Regarding the context switch, it doesn't happen in a thread but between two threads. Each core in a CPU can execute only one thread at a time for a time slice. You have a context switch, when one thread's work has not been completed in the given time slice. So it has to be paused and another thread being executed for it's time slice. Then the thread scheduler would schedule the paused thread to run at another time.

Upvotes: 4

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

My Question: There is option that in middle of the func DoWork, because of context switch etc', the continuous of the function will be in thread that is not 3?

No, context switch doesn't mean it goes to a different thread, just that processor core takes up a different thread / logic to process, this one still goes on the same thread. Most of the threads have same priority until and unless scheduled by CLR like GC or OS, which will have priority over other threads and freeze all other threads. Rest all have to keep on leaving processor core after some logical processing or I must say Processor core (Thread scheduling logic) keep scheduling other threads, thus not starving any of them. Please note at a given time, processor core can only schedule one thread / unit of work

Upvotes: 4

Related Questions