[英]Is creating instances of a class inside a static PageMethod thread safe?
我正在使用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页面吗?
从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...
}
}
您提供的示例看起来不错。 如果您正在重用一个对象的实例,那么我将确保该对象是线程安全的。
只要您不触摸任何共享资源,它就应该是线程安全的。
看看您的类是否是不变的,因为如果有人更改了它的状态,它将是一个新实例,您将不必担心线程问题,但是如果您要更改某些共享状态,则可以考虑同步,但是我认为您不需要任何线程同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.