在静态 PageMethod 线程中创建类的实例安全吗?
我正在使用 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 页面?
I am using jQuery to call PageMethods. For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods. Here is some sample code:
Sample #1
[WebMethod]
public static void PostComment(string comment)
{
UserAuth auth = new UserAuth();
if (auth.isAuthenticated)
{
//Post comment here...
}
}
Sample #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;
}
Will I be safe using these kinds of operations?
Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 http://msdn.microsoft.com/en- us/library/system.web.ui.page.aspx
“此类型 [Page] 的任何公共静态(在 Visual Basic 中共享)成员都是线程安全的。不保证任何实例成员都是线程安全的。”
因此,只要您的静态方法不接触类范围对象,您就应该没问题。例如,这可能很糟糕:
From http://msdn.microsoft.com/en-us/library/system.web.ui.page.aspx
"Any public static (Shared in Visual Basic) members of this type [Page] are thread safe. Any instance members are not guaranteed to be thread safe."
Therefore as long as your static methods don't touch class-scope objects you should be fine. e.g. this might be bad:
你给出的例子看起来不错。如果您要重用对象的实例,那么我将确保该对象是线程安全的。
The examples you gave look fine. If you were reusing an instance of an object, then I would make sure that object is thread safe.
只要您不接触任何共享资源,它就应该是线程安全的。
As long as you're not touching any shared resources, it should be thread safe.
看看你的类是否是不可变的,这意味着没有人可以改变它的状态,如果它被改变,它将是一个新的实例,你不需要担心线程问题,但如果你正在改变一些共享状态,你应该考虑同步,但我不认为您的情况需要任何线程同步。
see if your class is immutable that menas no one can change its state if it is changed it will be new instance than you won't need to worry about threading issues but if you are changing some shared state than you should think about synchronization but i don't think you need any thread synchronization in your case.