RE: Thread-safe Format

Oh, the joy of writing multiple threaded applications. I like this little tip that will keep string formatting calls from stepping over each other.

The Format function isn’t thread-safe unless you use the overload which takes a FormatSettings argument (because the FormatSettings-less version uses global variables). I use it to compose error messages in a thread I’m writing, and I want to use the same FormatSettings as the user would normally see in a GUI app. So here’s what I did. I added a TFormatSettings field to my thread class:

TMyThread = class(TThread)
FFormatSettings: TFormatSettings;
procedure Execute; override;

Then I set it at the start of the Execute method:

procedure TMyThread.Execute;
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, FFormatSettings);

This seems to work well.

[Via Craig Stuntz’s Weblog]