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?
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.