I create a class instance in a separate thread, and pass a method from the newly created class instance to the new thread .

Those. the main thread created 1 thread, which caused the 2nd thread.

  1. Can the last (2 thread) successfully close and free up resources in such a case?
  2. If an object created in the Main stream is transferred to the second stream, does the stream 2 close?
  • one
    worth adding sample code - Grundy

2 answers 2

  1. The system does not know where the object was created, it doesn’t care. Therefore, no matter what objects created the thread, this thread can end.

    But! A thread will be terminated if and only if its ThreadProc reaches the end. (Well, or if it is the main thread, then the Main function. Or if it is a background thread, then when the application starts to terminate.) When the thread dies does not depend [directly] on what objects it created.

  2. Same. Whether the stream will be completed and when, does not depend on whether the code of this stream works with the object. When the ThreadProc code reaches the end, the thread ends up.

  • OK, thanks for answer. And then how to deal with a memory leak? When the flow for some reason does not close. It turns out that because of some object that is used, it can not close? - Leonard Bertone
  • one
    @LeonardBertone: Please! // Not, a memory leak can not cause the stream to close. The fact that the thread does not end means that some code is running in it. Look for what this thread does. - VladD
  • I see, thank you - Leonard Bertone
  • And how can you know that the thread has worked, ie, closed? - Leonard Bertone
  • @LeonardBertone: Well, it depends on what tools you have. For example, in Visual Studio, you see a message in the Output window when the stream ends. Or if ThreadProc is in your hands, you can write something to the console or log ( new Thread(() => { DoSomeWork(); Console.WriteLine("Worker thread finished"); }).Start() . Or in In the Visual Studio pause mode, you can look at the Threads window and open the current call stack of this thread. And so on - VladD

The instantiated objects and threads are orthogonal. The objects you create in memory, the threads access this memory. At the same time, it is unimportant in which thread which object was created, except for two cases:

  • it is possible to work with UI controls only in the same thread in which they were created
  • Some COM components can only be operated in the same stream / context as they were created.

Objects do not affect the "successful closing" of the flow.