Asp.net C# 静态方法线程安全错误处理

发布于 2025-01-05 08:34:15 字数 477 浏览 3 评论 0原文

有时,您认为自己知道的简单事情会让您头脑发热......

我有一个 Asp.Net(表单)应用程序,它使用非静态类的静态方法对 PostBack 进行一些处理。这些方法需要返回 bool。

当静态方法中出现错误时,我不希望只是将异常抛出回页面级代码,而是在静态方法中显式处理它并返回 false。

我可能想得太多了,但是,如果 MyClass 有一个静态 ErrorMessage 字段,在页面中使用如下所示:

if(!MyClass.DoSomething){
  errorLabel.Text = MyClass.ErrorMessage; //Static ErrorMessage is set 
}

我对吗 ErrorMessage 实际上是线程安全的,因为 MyClass 是非静态的,页面存在于特定的 HttpContext 和变量中在回发时被销毁?

有什么理由不这样做,或者有更好的方法吗?

Sometimes its the simple things you thought you knew that make your head buzzz....

I have an Asp.Net (forms) application that uses the static methods of a non-static class to do some processing on PostBack. Those methods need to return bool.

When there is an error in a static method I would prefer not to just throw the exception back up to the page-level code, but rather explicitly handle it in the static method and return false.

I may be over-thinking this but, if MyClass has a static ErrorMessage field, used in the Page like this:

if(!MyClass.DoSomething){
  errorLabel.Text = MyClass.ErrorMessage; //Static ErrorMessage is set 
}

am I right that ErrorMessage is effectively thread-safe since MyClass is non-static, the Page lives within a specific HttpContext and variables are destroyed on PostBack?

Is there a reason not, or, a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫瑟鸿黎 2025-01-12 08:34:15

如果 ErrorMessageDoSomething 设置,则不是线程安全。如果在 if 测试之后和分配之前进行上下文切换,则它可能会被另一个线程重新分配。静态字段是静态的,与包含类是否静态无关。

摆脱 C 风格的返回代码并在错误时抛出异常。

If ErrorMessage is set by DoSomething, that is not thread safe. If you get a context switch after the if test and before the assignment, it could get reassigned by another thread. Static fields are static independent of whether the containing class is static or not.

Get rid of your C-style return code and throw an exception on error instead.

栖竹 2025-01-12 08:34:15

不,您的代码不是线程安全的。无论您的类是否静态,都可以访问静态变量并保留状态。在您的控制权返回之前,其他线程可以轻松修改 this 变量的内容。

No, your code is not thread safe. Irrespective of your class static or not, static variables can be accessed and retains the state. Other threads can easily modify content of the this variable before your control returns back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文