スレッド生成時にカレントスレッドのカルチャは引き継がれない
以下のコードを実行する。(Windowsから得られたカルチャは"ja-JP"とする)
CultureInfo cInfo = CultureInfo.CreateSpecificCulture("en-US"); Thread.CurrentThread.CurrentCulture = cInfo; Thread.CurrentThread.CurrentUICulture = cInfo; Thread newThread = new Thread(delegate(){}); Console.WriteLine(newThread.CurrentCulture == CultureInfo.CurrentCulture); Console.WriteLine(newThread.CurrentUICulture == CultureInfo.CurrentUICulture);
実行結果
False False
カルチャの情報は現在のカレントスレッドから子のスレッドに引き継がれると思っていたのだがそうではなく、あくまでWindowsで指定されたカルチャが引き継がれる。従って、明示的にO/Sの言語とは違うカルチャを設定した場合、その後に生成したスレッドのカルチャは整合が取れない。
整合を取るのであれば、スレッドを生成する度に親スレッド(スレッドを生成するスレッド)のカルチャを新たなスレッドに引き継がなくてはならない。
Thread newThread = new Thread(delegate(){}); newThread.CurrentCulture = CultureInfo.CurrentCulture; newThread.CurrentUICulture = CultureInfo.CurrentUICulture;
このような仕様になっているので、明示的にカルチャを固定するというのはしなくて良いのであれば止めた方が賢明のようだ。.NET C#に限ったことではないが、仮想な要素を持つ言語のスレッドはどこでどのように生成されているかが隠蔽されているからだ。
ちなみに、マネジドスレッドプール(ThreadPoolクラス)でも試してみたが、同様の結果となった。
追記
ちょっと古いがMSDNに記事があった。(記事が古いせいか残念ながら邦訳は無いようだ)
Let Your Apps Span the Globe with Windows Forms and Visual Studio .NET - MSDN Magazine>June 2002
In most cases, the culture for an application's user interface is set either implicitly using the Windows regional settings or explicitly through code. As you'll see when I discuss my Culture Explorer sample application, the current culture is specified on a per-thread basis. Each thread inherits the default Windows culture unless you change it by accessing the current thread through services provided by the System.Threading namespace.
仮に変更が無いとすれば.NET2.0以降も同様のはずだ。しかし....この仕様はどうなんだろう。