Search code examples
multithreadingdelphicom

Using CoInitialize in a Delphi thread


I am using TIdHttp and TXMLDocument inside a thread in a Delphi program. Now I want to know:

  1. Do these classes use COM objects so I need to call CoInitialize and CoUninitialize in this thread?
  2. If yes, do I have to use these functions at the body of execute method or at all methods that use TIdHttp or TXMLDocument classes?

Solution

    • TIdHTTP has no COM dependency.

    • TXMLDocument can have a dependency on COM. On Windows, out of the box it is a wrapper around Microsoft's MSXML ActiveX component, which uses COM. If you use another DOM vendor (for example, OmniXML, available from XE7) then there is no COM dependency. You can control this by setting the DefaultDOMVendor global variable.

    • CoInitialize and CoUninitialize must be called once from within the thread context. Typically in the Execute() method of TThread, as seen in this example flow:

      procedure TMyThread.Execute;
      begin
        try
          CoInitialize(nil);
          try
            while not Terminated do
            begin
              DoWorkThatMayUseCOM;
            end;
          finally
            CoUninitialize();
          end;
        except
          on E: Exception do
            // log exception
            Log(E);
        end;
      end;