If I access the variable with ThreadLocal using Task, will it (variable) be destroyed after the thread ends? Or will it be available for this stream later?
1 answer
The lifetime of thread local-variables is limited only by the lifetime of the thread. So the variable will exist if the stream does not die.
The problem is usually different: using Task, you do not control in which thread your code will be executed. Two consecutive runs of even the same Task can be executed from different threads (and the Task itself can migrate from stream to stream), so transferring data through a thread local variable is not a good idea.
- Still, Task itself cannot migrate from stream to stream. - Pavel Mayorov
- @PavelMayorov: Why can not? On any
await's can the same. Plus, the concept of “flow in which a task runs” is in itself incorrect. What if the task is waiting to read from the network? What if task performsawait Task.WhenAll(...), and the expected tasks run in different threads? - VladD - The task is generally rarely considered to be running ... ideone.com/N2YSyH - Pavel Mayorov
- @VladD I need it. I want to make a method call in a lot of flow not Box.Push ("an object," an object that is pushed "," an object that pushes "), but Player.Box (" the name of an object that is being pushed "). Push (). Т .e created a player before, and then call similar methods on his behalf.The Box method returns a Box object, which is ThreadLocal. As a result, no locks are needed and less time is spent on initializing objects - Arantler
- @Arantler: Passing an object reference to Task takes an extra few nanoseconds. You save on matches. - VladD
|