Multithreading improvements in .NET 4

前端 未结 3 1990
天涯浪人
天涯浪人 2020-12-23 02:24

I have heard that the .NET 4 team has added new classes in the framework that make working with threads better and easier.

Basically the question is what are the new

3条回答
  •  渐次进展
    2020-12-23 02:46

    Yes, .NET 4 added the Task Parallel Library which, at a high level, adds support for:

    • running parallel loops with Parallel.For and Parallel.ForEach
    • create or run tasks using Parallel.Invoke or the Task class
    • PLINQ (parallel LINQ to Objects)

    Answering the update to the original question...

    The TPL is the preferred way of writing parallel tasks using .NET 4. You can still create threadpool items yourself, and do all of the same "manual" threading techniques you could before. The thing to keep in mind is that the entire threadpool (and pretty much everything threading related) has been rewritten to take advantage of the TPL. This means that even if you create a threadpool item yourself you still end up using the TPL, even if you don't know it. The other thing to keep in mind is that the TPL is much more optimized, and will scale more appropriately based on the number of available processors.

    As for knowing what situation each of them would be best suited for, there is no "silver bullet" answer. If you were previously queueing your own threadpool item (or otherwise doing something multi-threaded) you can modify that portion of your code to use the TPL without any consequences.

    For things like parallel loops or parallel queries, you will need to analyze the code and the execution of that code to determine if it is appropriate to be parallelized.

提交回复
热议问题