Does the thread identity get transferred when using PLINQ Extensions?

后端 未结 3 1493
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 13:51

I am using .AsParallel().ForAll() to enumerate a collection in parallel in the context of an ASP.NET request. The enumeration method relies on System.Threading.Thread.CurrentPr

3条回答
  •  抹茶落季
    2021-02-15 14:22

    One subtle thing to notice when passing Principal through .AsParallel() boundary: Where your sequence gets materialized?

    This isn't a problem with .ForAll(), but consider another scenario:

    var result = items.AsParallel().Select(MyTransform);
    

    Then you're passing result elsewhere so that it crosses thread boundary (which is likely, say, if you're returning it out of WCF action method).

    In this case by the time MyTransform gets applied, Thread.CurrentPrincipal value might contain something unexpected.

    So, the workaround here is to materialize query on the spot (by calling .ToArray(), .ToList(), etc.)

提交回复
热议问题