I have a web service and some methods and I do NOT want to use this code below, which works fine, because I intend to use this in a multi-threaded app where static (I have read) is not thread safe.
So, what I have done now is simply repeat the code that is in the static method 'returnisTrue()' below, in the body of my web service method "myWebMethod", at points //1 of 3, //2 of 3, and //3 of 3. This works fine but results in bloated code. Is there a more compact way, using functional programming or anonymous methods or what have you that I can use?
Note the compiler choked when I tried to create a class inside the method...which would have solved my problem.
As I say the code I have now works fine but it is bloated, as I repeat the 'static' method 'returnisTrue' three times.
Thank you.
EDIT: in response to some questions about making my static method thread safe, which I rather not bother with, but in the interest of getting a solution I include below.
All this code is server side in a web service
// I cannot unfortunately use this static method below--not thread safe
static private bool returnisTrue()
{
bool isTrue = false;
// do a bunch of stuff here
return isTrue;
}
public bool myWebMethod (string XYZ)
{
//public Class myClassReturnisTrue { … } //will not compile
bool isTrueOrNot1 = returnisTrue(); //1 of 3
/// more code here
bool isTrueOrNot2 = returnisTrue(); //2 of 3
///more code here
bool isTrueOrNot3 = returnisTrue(); //3 of 3
return isTrueOrNot1 && isTrueOrNot2 && isTrueOrNot3;
}
// here is the static method 'returnisTrue' it looks something like this:
static private bool returnIsTrue(string A, string B)
{
if (A.Length() < B.Length())
{
return true;
}
else
return false;
}
What are you actually doing within your static method? Are you modifying any global state or are you only working on local variables? There is nothing wrong with using static methods, or even variables, as long as you take proper measures to make sure that your code within is actually thread-safe.
Both static methods and instance methods can potentially be unsafe depending on what you are doing within them. The main question to ask is, are you accessing any data that is accessible between multiple threads within your method? And if so, why not change your method to be thread-safe (through for example locking).
Take a look for example at the .NET framework itself, it contains various static thread-safe methods throughout.
Edit:
Ok, now that we've seen your method - it is indeed thread-safe already. The method is not accessing any shared data and strings are immutable and inherently thread-safe as a result.