Friday, September 19, 2008

Delphi and C++Builder 2009 - TApplication is Apartment Threaded

In Delphi 2009 and C++Builder 2009 (AKA Tiburon) by default the main thread of a VCL application will be apartment threaded. Take a look at TApplication.Create for the details. This isn't really a change from previous versions of VCL but the location of the call and how to override it is new. And now VCL calls OleInitialize instead of CoInitialize so there is a slight behavior change.

There may be reasons why a developer won't want this default behavior and the best way of doing this is to create this unit:

unit InitCom;

interface

implementation

uses
  ActiveX;

var
  NeedToUninitialize: Boolean;
initialization
  NeedToUninitialize := Succeeded(CoInitializeEx(nil, COINIT_MULTITHREADED));
finalization
  if NeedToUninitialize then
    CoUninitialize;
end.

And place it in the .dpr as the first unit (it must be before Forms or anything that brings in Controls).

It isn't recommended to run any UI under a multithreaded apartment but this will allow those who need it to change the default threading model.

Here is a blog post by Raymond Chen about why running the UI thread as multithreaded isn't a good idea.

2 comments:

Jouni Aro said...

Also note that CoInitFlags is no longer used to define the threading model in Delphi 2009 (although the Help still has the old description for it).

Soul Intruder said...

Still valid, thank you!

Post a Comment