Search code examples
c#multithreadingplinq

Can P-Linq switch threads during the delegate execution?


Is it possible for a context switch during the execution of the delegate to switch executing threads?

I tried this snippet in LinqPad a few times, and it does not hit the new Exception() line, which seems to indicate that it will continue on the original thread, but maybe my little test here is inadequate to test this, I'm just not sure.

void Main()
{
    var list = Enumerable.Range(1,100000);
    list.AsParallel().ForAll( i=>
    {
        var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
        System.Threading.Thread.Sleep(0); // allow a context switch
        work(i,threadId); 
    });
    "Complete".Dump();
}

void work(int num,int threadId)
{
    var currentId = System.Threading.Thread.CurrentThread.ManagedThreadId;
    if(threadId!=currentId)
    {
        throw new Exception();
    }
}

Solution

  • When a Task is Scheduled it will always and forever use the first Thread assigned to it. That Thread may stop running and let another Thread (from the thread pool or not) do some work, and the entire process could be halted to let another process do some work, but no matter what you'll always end up back in the thread you started in.