C # creating a shared instance

My question is why this line - ThreadTest tt = new ThreadTest();in the example below creates a shared instance, not a separate instance. Please advise, thanks!

class ThreadTest
{
  bool done;

  static void Main()
  {
    ThreadTest tt = new ThreadTest();   // Create a common instance
    new Thread (tt.Go).Start();
    tt.Go();
  }

  // Note that Go is now an instance method
  void Go() 
  {
     if (!done) { done = true; Console.WriteLine ("Done"); }
  }
}

EDIT: An example from http://www.albahari.com/threading/#_Introduction that demonstrates how to exchange data between threads.

EDIT2: My question is exactly why "the instance is common to both threads"

+3
source share
3 answers

It is unclear what you mean by “shared instance”, but the constructor definitely creates a new instance. The method Gois executed twice, once in a new thread and once in the main thread.

, , , Go .

Go . "" .

+4

, tt.Go 'done', , , . , , , .

ThreadTest, Go, !

+1

6 , , . , , , (). , .

new Thread (Go).Start();
Go();

TT, . .

ThreadTest tt = new ThreadTest();
new Thread (tt.Go).Start();
tt.Go();

, , .Go , , , tt- ( .Go), 3. .Go tt, tt- done. Afaik, "", .

Also: I'm still shaky in several aspects of slicing. One riddle for me is what exactly happens to tt when it is executed new Thread (tt.Go).Start();... tt was created in the original thread, but now it lives in both cases. Is byref / byval used or is something else going on? Is it more accurate to say that the tt object does not actually "live" or "belongs" to any of the threads, but rather to a heap, and therefore both threads must have access to it?

+1
source

Source: https://habr.com/ru/post/1762255/


All Articles