ASP.net 中的静态方法

zXS*_*dXz 2 c# asp.net static-methods

我目前正在构建一个 ASP.NET Web 应用程序。我想创建一些静态方法作为辅助方法。这是个好主意还是我以后会遇到问题?没有字段或属性。只是方法,有些有返回类型,有些没有返回类型。

静态方法是否在所有用户之间共享(例如字段和属性)还是唯一的?


    private static string userName;
    public static string UserName
    {
        get
        {
            if (User.Identity.IsAuthenticated)
            {
                if (userName == "" || userName == null)
                {
                    userName = User.Identity.Name;
                }
                return userName;

            }
            else
            {
                throw new ArgumentNullException("Illegal Access", "You're not login or authorize to perform such task");
            }


        }
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*ers 5

是的,它们是共享的,但是您认为这对于方法意味着什么?

静态方法在 ASP.NET 中是完全安全的。即使该方法被多个用户在多个请求中多次调用,调用之间也不存在共享数据。

也就是说,除非静态方法修改了静态数据,在这种情况下,你应该尽可能避免,但无论如何,都需要加锁。


Public Class MyPage
    Inherits Page

    Private Shared _iAmShared As Integer

    Private Shared Sub StaticMethod()
        Dim iAmNotShared As Integer = 0
        _iAmShared = _iAmShared + 1
        iAmNotShared = iAmNotShared + 1
    End Sub

    Public Sub Page_Load()
        StaticMethod()
    End Sub
End Class
Run Code Online (Sandbox Code Playgroud)

上面的代码是错误的。的增量_iAmShared需要互锁。如果(当)多个请求同时执行该代码,则不能保证增量是原子的。有一份_iAmShared所有用户和所有请求

另一方面,iAmNotShared根本不共享。每次调用都会StaticMethod获取其自己的iAmNotShared.