multithreadingdelphicomdelphi-xe5apartments

Unable to set thread concurrency model to multithreaded apartment


I've created a new DUnit Test Project and I am trying to setup multithreaded apartment at its start. The problem is that on one computer apartment type is changed.

program COMApartment;

{$IFDEF CONSOLE_TESTRUNNER}
{$APPTYPE CONSOLE}
{$ENDIF}

uses
  Winapi.ActiveX,
  TestuApartmentInfo in 'TestuApartmentInfo.pas',
  DUnitTestRunner;

{R *.RES}

begin
  CoUninitialize;
  CoInitializeEx(nil, COINIT_MULTITHREADED); // Result is S_OK
  Log(GetCurrentApartmentType); //APTTYPE_MTA on both computers.
  DUnitTestRunner.RunRegisteredTests;
end.

Now, when I run this simple test:

unit TestuApartmentInfo;

interface

uses
  TestFramework, Winapi.Windows, uApartmentInfo;

type
  TestIComThreadingInfo = class(TTestCase)
  published
    procedure ApartmentType;
  end;

implementation

uses
  Dialogs, System.SysUtils;

procedure TestIComThreadingInfo.ApartmentType;
begin
  //This gives APTTYPE_MTA on my dev computer (Windows 7) and APTTYPE_MAINSTA or APTTYPE_STA on virtual machine (Windows 2007 Server).
  Log(GetCurrentApartmentType); 
end;

initialization
  RegisterTest(TestIComThreadingInfo.Suite);
end.

I don't understand different behaviour on different computers. Is this due to different operating systems? In my test I could spawn another thread and specify apartment model for it and it would work, but my curious nature wants to know why different results in above case.

GetCurrentApartmentType has been implemented as in this article and it works properly. This is a sample application to illustrate problem which I have with some COM objects that need to run in multithreaded apartment model.


Solution

  • Solution to my problem is described in this post. My mistake was calling CoUninitialize/CoInitialize after some other code already called it. CoInitialize should be called before any other code.