gpt4 book ai didi

c# - 静态委托(delegate)是线程安全的吗?

转载 作者:行者123 更新时间:2023-11-30 15:10:39 25 4
gpt4 key购买 nike

考虑这个代码片段:

public static class ApplicationContext
{
private static Func<TService> Uninitialized<TService>()
{
throw new InvalidOperationException();
}

public static Func<IAuthenticationProvider> AuthenticationProvider = Uninitialized<IAuthenticationProvider>();
public static Func<IUnitOfWorkFactory> UnitOfWorkFactory = Uninitialized<IUnitOfWorkFactory>();
}

//can also be in global.asax if used in a web app.
public static void Main(string[] args)
{
ApplicationContext.AuthenticationProvider = () => new LdapAuthenticationProvider();
ApplicationContext.UnitOfWorkFactory = () => new EFUnitOfWorkFactory();
}

//somewhere in the code.. say an ASP.NET MVC controller
ApplicationContext.AuthenticationProvider().SignIn(username, true);

在多线程可以调用它们的意义上,静态类 ApplicationContext 中的委托(delegate)是否是线程安全的?

如果我采用这种方法,我会面临哪些潜在问题?

最佳答案

Are delegates in the static class ApplicationContext thread-safe in the sense that multiple-threads can invoke them?

是的。但委托(delegate)仅与其指向的方法一样线程安全。

因此,如果您的 AuthenticationProvider 调用的方法和 UnitOfWorkFactory委托(delegate)是线程安全的,那么您的委托(delegate)也将是线程安全的。

在您提供的代码中,这些只是构造函数调用。它实际上并没有比这更线程安全(除非您的构造函数中有一些疯狂的线程逻辑——我当然希望不会)。

What potential problems will I face if I pursue this approach?

没有直接由调用您的委托(delegate)产生的结果。同样,您应该担心的关于线程安全的唯一问题是那些与您的委托(delegate)调用的实际方法有关的问题(在本例中,是 LdapAuthenticationProviderEFUnitOfWorkFactory 的构造函数)。

更新:limpalex 做了一个很好的观察:在您发布的代码中,您实际上调用 Uninitialized<TService> ApplicationContext 的静态构造函数中的方法类,它会抛出异常。您要做的是分配您的委托(delegate)给该方法。我想你想要的是这样的:

// note: changed return type to TService to match Func<TService> signature
private static TService Uninitialized<TService>()
{
throw new InvalidOperationException();
}

// note: removed () symbols to perform assignment instead of method call
public static Func<IAuthenticationProvider> AuthenticationProvider = Uninitialized<IAuthenticationProvider>;
public static Func<IUnitOfWorkFactory> UnitOfWorkFactory = Uninitialized<IUnitOfWorkFactory>;

关于c# - 静态委托(delegate)是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3043258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com