Why can a local variable be accessed in another thread created in the same class?

后端 未结 5 496
误落风尘
误落风尘 2021-01-31 11:38

I couldn\'t really find anything on this exact topic, so please lead me toward the right direction, if a question already exists.

From what I have learned about .NET, it

5条回答
  •  -上瘾入骨i
    2021-01-31 12:07

    I'm a bit late and the answer @Eric J. gave is wonderful and to the point.

    I just want to add a bit of clarity to another issue in your perception of threads and variables.

    You said this in your question's title "variable be accessed in another thread". Adding to that is the fact that in your code, you're accessing your variable from exactly 1 thread which is the thread that gets created here:

        Thread thread = new Thread(new ThreadStart(DoSomething));
        thread.IsBackground = true;
        thread.Start();
    

    All these things made me realize that you were scared that a thread different from the one that actually creates the instance of MyClass will use something from inside that instance.

    The following facts are important for a clearer view of what multithreading is (it's simpler that you thought):

    • threads don't own variables, they own stacks and stack could contain some variables but that's not my point
    • there is no intrinsic connection between the thread on which an instance of a class gets created and that thread. It is owned by all threads the same way it is not owned by any of them.
    • when I say these things I'm not talking about thread stacks but one might say that threads and instances are two sets of independent objects which simply interact for the greater good :)

    EDIT

    I see the words thread safety appeared on this thread of answers. In case you're maybe wondering what those words mean I recommend this great article by @Eric Lippert: http://blogs.msdn.com/b/ericlippert/archive/2009/10/19/what-is-this-thing-you-call-thread-safe.aspx

提交回复
热议问题