1

If I have the following program

public class MainClass {
    public static void Main () {
        Console.WriteLine($"Main [{Thread.CurrentThread.ManagedThreadId}]");
        
        Parallel.Invoke(
            () => Foo(),
            () => Bar()            
        );
        
        Console.WriteLine("Done");
    }

    static void Foo() {
        Console.WriteLine($"Foo[{Thread.CurrentThread.ManagedThreadId}]");
    }

    static void Bar() {
        Console.WriteLine($"Bar[{Thread.CurrentThread.ManagedThreadId}]");
    }
}

then under .net core 3.1 will it produce output like

Main [1]
Foo[1]
Bar[4]
Done

My question now is it guaranteed that Parallel.Invoke() will use it's calling thread to do some or all the work that it is given? Like will this be on every platform or framework or does it behave differently on some UI Frameworks like WPF or WinForms.

My question also is not whether it will block the calling thread or not but whether the calling thread will do some of the work.

For example could the output of the above code be

Main [1]
Foo[2]
Bar[3]
Done
Ackdari
  • 3,222
  • 1
  • 16
  • 33
  • 6
    What would you do differently if the answer is no? – Damien_The_Unbeliever Aug 21 '20 at 12:28
  • 3
    I was thinking we need a new close reason "Unclear *why* are you asking". You can look into [source](https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Parallel.cs,ee8cd9c2cf5b8e41) to self-answer such questions, but really - what are you going to do with such a knowledge? It feels like [XY problem](https://meta.stackexchange.com/q/66377/299295). – Sinatr Aug 21 '20 at 12:34
  • 2
    It depends on TaskScheduler. – Alexander Petrov Aug 21 '20 at 14:04
  • 1
    `Parallel.Invoke` anyway blocks caller `Thread` while executing till all fired delegates is finished. By design. Thus to optimize the execution it uses the main `Thread` for a first called delegate. But yes, it depends on `TaskScheduler`. – aepot Aug 21 '20 at 18:33

0 Answers0