lock and overloads

  • Thread starter Thread starter am_public
  • Start date Start date
A

am_public

Hi,
I have to do a sealed class with some functions that ruturns me a
string with a required length.

I.e.

public class MyClass
{
static Object lockStringFixedLength = new Object();

public static string GetStringFixedLength(
string stringToChange,
int length,
char charToUse,
bool insertAtLeft,
bool cutIfLonger
)
{
lock( lockStringFixedLengthString )
{
string fixedString = "";

if ( stringToChange.Length == length )
return stringToChange;

if ( stringToChange.Length < length )
{
string stringToAdd =
new string( charToUse, length - stringToChange.Length );

if ( insertAtLeft )
{
fixedString = stringToAdd + stringToChange;
}
else
{
fixedString = stringToChange + stringToAdd;
}
}
else
{
fixedString = ( cutIfLonger )
? stringToChange.Substring( 0, length )
: stringToChange;
}

return fixedString;
}
}


I need to add many overloads for default options.

I.e.

public static string GetStringFixedLength(
string stringToChange,
int length,
char charToUse
)
{
return GetStringFixedLength(
stringToChange,
length,
charToUse,
false,
true
);
}


public static string GetStringFixedLength(
string stringToChange,
int length
)
{
return GetStringFixedLength(
stringToChange,
length,
' ',
false,
true
);
}


Should I declare and create a static object for every overload to use
in a lock block, or can I do something else? I need many overloads
(more than 20, and I need to write many other functions with a lot of
overloads in the same class).

Some tips?

Thanks a lot.
 
Depending on what you are doing, each overload could perhaps call the same
full featured function with appropriate default values ?

This way you would have a single code path and the other overloads are just
making a call to the same full featured function providing default values...
 
Yes, all funtion will call the full one with appropriate default
values.

So, I do not need to use lock?

I think I should study a little more aboute threading...

Thanks a lot!
 
You still need to lock the function that all other overloads end up
calling.

Regards
Senthil
 
Not that familiar but if you are using the same code path you'll end up with
locking your critical resource. As a side note I'm not sure it's needed
here. What is the critical resource you are trying to protect ? It looks
like you are using just static methods but they don't share any static
fields or whatever.

How could they use the same shared data ?

Let me know about your findings. I'm myself not well versed in threading...
 
I need to share an HashTable, in some other functions.
However now I think I know how avoid problems on overloading.
Probably I will need help for other things.
Thanks a lot.
 
Back
Top