在静态PageMethod线程中创建类的实例是否安全?

时间:2010-12-14 15:19:01

标签: c# asp.net static-methods pagemethods

我正在使用jQuery来调用PageMethods。对于某些操作,必须验证当前用户凭据,对于其他操作,我需要调用其他静态方法。以下是一些示例代码:

样本#1

[WebMethod]
public static void PostComment(string comment)
{
    UserAuth auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}

样本#2

[WebMethod]
public static string GetComment(int commentId)
{

    commentDto comment = //get comment data from the database...
    string friendlyDate = ConvertFriendlyDate(comment.commentDate);

    return friendlyDate + " " + comment.text;
}

public static string ConvertFriendlyDate(DateTime commentDate)
{
    string friendlyDate = //call static utility method to convert date to friendly format

    return friendlyDate;

}

使用这些操作我会安全吗?

我最好放弃页面方法,只为我的AJAX请求调用一个单独的ASPX页面吗?

4 个答案:

答案 0 :(得分:1)

来自http://msdn.microsoft.com/en-us/library/system.web.ui.page.aspx

“此类型[Page]中的任何公共静态(在Visual Basic中为Shared)成员都是线程安全的。不保证所有实例成员都是线程安全的。”

因此,只要您的静态方法不接触类范围对象,您应该没问题。例如这可能不好:

static UserAuth auth;
[WebMethod]
public static void PostComment(string comment)
{
    auth = new UserAuth();
    if (auth.isAuthenticated)
        {
            //Post comment here...
        }
}

答案 1 :(得分:0)

你给出的例子看起来很好。如果您正在重用对象的实例,那么我会确保该对象是线程安全的。

答案 2 :(得分:0)

只要您没有触及任何共享资源,它就应该是线程安全的。

答案 3 :(得分:0)

看看你的类是不可变的,没有人可以改变它的状态,如果它被改变它将是新的实例,你不需要担心线程问题,但如果你改变一些共享状态,你应该考虑同步,但我不认为你的情况下需要任何线程同步。