简体   繁体   中英

Static Method in ASP.net

I'm currently building an asp.net web application. I want create some static method as helper methods. Is it a good idea or would I run into problems later on? No fields or properties. Just methods, some with return type and some with no return type.

Is static method shared across all users like fields and properties or are they unique?


    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");
            }


        }
    }

Yes, they are shared, but what do you think that means for a method?

Static methods are perfectly safe in ASP.NET. Even if the method is called multiple times by multiple users in multiple requests, there is no shared data between the calls.

That is, unless the static method modifies static data, in which case, you should avoid if possible, but in any case, need to lock.


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

The code above is wrong. The increment of _iAmShared needs to be interlocked. If (when) multiple requests execute that code at the same time, there is no guarantee that the increment will be atomic. There is one copy of _iAmShared for all users, and all requests.

On the other hand, iAmNotShared is not shared at all. Each call to StaticMethod gets its own copy of iAmNotShared .

Static methods are great for helper functions in an ASP.net website. You can create a helper class with static functions that can be used throughout the site. Each call to the static method is unique and nothing is shared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM