0
多くのコードが削除されましたが、実際にこの部分だけを表示する必要があります。主な考え方:メソッドローカライズ()はすばやく動作する必要があるため、他のスレッドでロックしてはいけません。フラグisLoadedを使用して、使用するローカライゼーションのタイプ(OldまたはCurrent)を検出します。このコードはスレッドセーフですか? C#
static class Localization
{
static readonly object locker = new object();
static string LocalizationDir;
static bool isLoaded;
static Tuple<string, string> OldLanguage;
static Dictionary<string, string> OldLocalization;
static Dictionary<string, string> CurrentLocalization;
public static Tuple<string, string> CurrentLanguage {
get;
private set;
}
static Localization() {
lock (locker) {
OldLanguage = null;
CurrentLanguage = new Tuple<string, string>("en", "English");
isLoaded = true;
OldLocalization = null;
CurrentLocalization = null;
}
}
public static bool SetLanguage(string languageShortName) {
lock (locker) {
string languagePath = Path.Combine(LocalizationDir, languageShortName + ".loc");
// save localization, be ready to return it back
OldLocalization = CurrentLocalization;
OldLanguage = CurrentLanguage;
isLoaded = false;
try {
using (TextReader i = new StreamReader(languagePath)) {
/*
Parse file,
Modify CurrentLocalization, CurrentLocalization
*/
}
}
catch (Exception e) {
// Just return back our good localization data
CurrentLocalization = OldLocalization;
CurrentLanguage = OldLanguage;
isLoaded = true;
OldLocalization = null;
OldLanguage = null;
return false;
}
// everything is good
{
OldLocalization = null;
OldLanguage = null;
isLoaded = true;
UpdateControls();
}
return true;
}
}
// <summary>
// We think that there are no bugs in this method
// No locking
// </summary>
public static string Localize(this string Text) {
if (CurrentLanguage.Item2 == "English")
return Text;
Dictionary<string, string> ChoosedLocalization = null;
if (!isLoaded && OldLocalization != null)
ChoosedLocalization = OldLocalization;
else if (isLoaded && CurrentLocalization != null)
ChoosedLocalization = CurrentLocalization;
if (ChoosedLocalization != null) {
string Translate;
if (!ChoosedLocalization.TryGetValue(Text, out Translate))
return Text;
else
return Translate;
}
else
return Text;
}
}
'Localize'の間に' CurrentLanguage'が変わるのを止めるにはどうすればいいですか? –
ああ、何もない。私はCurrentLocalizationで書いたように書き直す必要があります。 –
'ChoosedLocalization = OldLocalization; (もしisLoaded && OldLocalization!= null) 'の中で、ChoosedLanguage = OldLanguage; –