简体   繁体   English

ASP.net中的静态方法

[英]Static Method in ASP.net

I'm currently building an asp.net web application. 我目前正在构建一个asp.net Web应用程序。 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. 静态方法在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. _iAmShared的增量需要互锁。 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. 所有用户和所有请求都有一个_iAmShared副本。

On the other hand, iAmNotShared is not shared at all. 另一方面, iAmNotShared不共享iAmNotShared Each call to StaticMethod gets its own copy of iAmNotShared . 每次对StaticMethod调用都会获得其自己的iAmNotShared副本。

Static methods are great for helper functions in an ASP.net website. 静态方法非常适合ASP.net网站中的辅助函数。 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. 每次对静态方法的调用都是唯一的,并且不共享任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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