What "Current" properties flow with ExecutionContext
Asked Answered
C

1

8

This is a two part question:

  1. Can someone provide a list of the ASP.NET/.NET properties that are typically thread local that flow with ExecutionContext?

    HttpContext.Current? Thread.CurrentContext? Thread.CurrentPrincipal? Thread.CurrentCulture?

    What properties can I count on surviving/persisting async/await?

    What else?

  2. Is there any way to add application specific Context information that will flow automatically with ExecutionContext? Something like

    var ec = ExecutionContext.Capture();
    ec.CustomContext["MyCustomContext"] = ACustomContext;
    
Chimb answered 21/6, 2013 at 18:33 Comment(4)
What are you actually trying to do? Why do you feel the need to store a custom context?Fideism
If you have two separate questions, you should ask two questions.Rollandrollaway
@ReedCopsey, I'm trying to refactor some legacy code that makes use of ThreadStatic and other thread local storage mechanism so that it will play nice with async/await.Chimb
@JoeEnzminger, you may want to check this: referencesource.microsoft.com/#mscorlib/system/threading/…Nola
P
14

The best resource for this is ExecutionContext vs. SynchronizationContext by Stephen Toub. There is no list of properties like what you're looking for.

ASP.NET actually uses SynchronizationContext to flow HttpContext.Current, and treats Thread.CurrentPrincipal rather oddly.

You can add your own context using LogicalSetData/LogicalGetData. However, you should only store immutable data. I document this on my blog.

Poorhouse answered 21/6, 2013 at 18:41 Comment(5)
Thanks (for LogicalSetData/LogicalGetData). I'd read each article you mentioned already, but it still left open the question of what framework context's flow. Seems like something that would be important to document...Chimb
@JoeEnzminger: BTW, I don't recommend logical get/set data. It's just possible to use if you can't find another solution. I haven't run benchmarks but I would expect it's much slower than ThreadStatic. Explicit method arguments or instance fields would be my solution of choice.Poorhouse
+1. It's interesting to see what actually gets flowed, albeit undocumented: referencesource.microsoft.com/#mscorlib/system/threading/…. Especially interesting how synchronization context gets flowed explicitly via ExecutionContext.Run, but not implicitly.Nola
@Noseratio if you read Toub's linked article (specifically the last paragraphs) you'll see that SynchrnoizationContext is actually not flowed most of the time (not sure what you meant by explicitly/implicitly).Animator
@OhadSchneider, by explicitly I meant calling ExecutionContext.Capture and ExecutionContext.Run explicitly. By implicitly I meant just letting the async/await infrastructure flow it.Nola

© 2022 - 2024 — McMap. All rights reserved.