none
Parallel.ForEach: Can I set thread name when I am using Parallel.ForEach? RRS feed

  • Question

  • I am using following C# code to process request.

    Parallel.ForEach(reqs, parallelOptions, req => ProcesRequest(req));


    Inside ProcesRequest method can I set thread name. See following code:

    Thread.CurrentThread.Name = "Some name with " + i;

    Please suggest if above code is will give consistent thread names.

    Is it fine to write such code. And does it affect when lot of threads will get created.

    Is there any reusing of threads happens internally?

    • Edited by Omkaraaa Wednesday, April 4, 2018 2:03 PM
    Wednesday, April 4, 2018 2:01 PM

Answers

  • Hi Omkaraaa,

    >> if above code is will give consistent thread names.

    It will give different names based on “i” parameter.

    >> Is there any reusing of threads happens internally?

    Yes, it will reuse the threads when previous threads finished.

    >> Is it fine to write such code. And does it affect when lot of threads will get created

    Thread.Name property is write-once, you will receive exception when you try to set name for a thread whose name already set.

    For your above code, it will throw exception when it reuses previous thread and set the name property.

    Best Regards,

    Tao Zhou


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Omkaraaa Thursday, April 5, 2018 11:27 AM
    Thursday, April 5, 2018 2:31 AM