Does the COM object cause CLR to free when the thread that created it terminates?

I was not able to figure out how to look for confirmation on this suspicion, but I see evidence that the COM object created in one thread is no longer available for other threads (the COM object that was separated from its base RCW cannot be used ) when the code stops executing in the thread that created it (and this thread can be terminated). This is a very insidious problem for tracking, because I have calls to System.Runtime.InteropServices.Marshal.ReleaseComObjectall of my code, but I could not determine that one of them was called, causing this error. Finally, I came to the conclusion that the COM object was apparently implicitly freed when the secondary thread stopped executing. Could this be true? Is this documented behavior?

+4
source share
2 answers

Yes, a COM object tends to have an affinity for flow. Threading is not a minor part of a COM implementation. Unlike .NET, COM provides thread safety guarantees for a COM class. COM can publish the kind of streaming it supports, and "flat" (i.e., "Non-thread safe") is a very common choice. COM ensures that these requirements are met if the program does not do anything to help. Marching a call from one thread to another so that the object is always used in a thread-safe manner is automatic. In .NET code, you usually have to do it yourself, for example, using Control.BeginInvoke or Dispatcher.BeginInvoke.

, , COM-, , . , . . , , , . , , , Dispatcher.BeginInvoke .NET.

Fwiw, , Marshal.ReleaseComObject() . -, . GC COM . . , COM- , , , .NET, : GC.Collect() . , Marshal.ReleaseComObject() .

+6

, . 1, , , 2 , "COM-, RCW, ".

Public Class Form1

   Dim comRef As Microsoft.Office.Interop.Outlook.Application

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim t As New System.Threading.Thread(AddressOf CreateApplication)
      t.SetApartmentState(Threading.ApartmentState.STA)
      t.Start()
   End Sub

   Private Sub CreateApplication()
      comRef = New Microsoft.Office.Interop.Outlook.Application
   End Sub 

   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      TextBox1.Text = comRef.DefaultProfileName
   End Sub
End Class
0

All Articles