我通常会建议不要实现诸如双重检查锁定之类的微妙机制,尤其是当您已经在 BCL 中实现了它们时。在这种情况下:
public class SafeInitializater
{
private bool _initialized;
private object _dummy;
private object _syncLock;
public void InitializeOnce(Action initializer)
{
LazyInitializer.EnsureInitialized(ref _dummy, ref _initialized, ref _syncLock,
() => {
initializer();
return null;
});
}
}
使用示例:
var initializer = new SafeInitializater(); //or you could make this static somewhere
var t1 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
var t2 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
await Task.WhenAll(t1, t2);