我需要控制新线程的创建,所以它们总是具有主线程的一些特征。为了做到这一点,我使用一个类ThreadFactory,我设置CurrentCulture和currentuicculture。
public static class ThreadFactory {
public static Thread Create(ThreadStart start) {
var thread = new Thread(start);
thread.CurrentCulture = CultureInfo.CurrentCulture;
thread.CurrentUICulture = CultureInfo.CurrentUICulture;
return thread;
}
}
例如,如果我想创建一个新的线程,它将被初始化为CurrentCulture = windows设置,比如english。如果我将主线程更改为西班牙语,则新主线程仍将是英语。由于这种行为,我总是使用ThreadFactory以这种方式创建新线程:
Thread t1 = ThreadFactory.Create(() => {
//Thread code
});
t1.start();
这样做,我确信新线程总是以与主线程相同的文化开始,不需要在每个线程代码中更改。问题是,我想有一个工作方式与CurrentCulture相同的属性。我尝试使用ThreadStatic属性,但它在子线程中初始化为空值。并且使用它作为静态属性是不可能的,因为我需要它是线程安全的主线程。
我也有同样的问题很久以前,然后我发现这个,你可以把你想要的一切在那个线程:
private static void CreateThread()
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
var currentUICulture = Thread.CurrentThread.CurrentUICulture;
var thread = new Thread(() =>
{
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentUICulture;
// Do something here, example:
Thread.Sleep(5000);
}) {IsBackground = true};
thread.Start();
}