How to make a Thread Safe Shared Function

  • Thread starter Thread starter Aaron Cutlip
  • Start date Start date
A

Aaron Cutlip

I have been looking all over and have seen many possible ways to create a
Syncronized Shared Function in VB.NET, but I would like some advice that
will make my life easier. Given the following code how do I ensure that the
two methods are thread safe?

Public Class Class1
Public Shared Function addMe(ByVal i1 As Integer, ByVal i2 As Integer)
As Integer
Return i1 + i2
End Function

Public Shared Function makeString(ByVal s1 As String, ByVal s2 As
String) As String
Return s1.ToLower + s2.ToUpper
End Function
End Class

I know that I could put SyncLock in each of the methods or that I could use
"<Synchronization()> Public Class Class1 Inherits ContextBoundObject", but I
have a lot of code that needs updated and was also thinking that SyncLock
and that Syncronizing the entire class is a memory issue. Essentially what
I want to do is create a Public Shared Syncronized method.

Thanks,

-Aaron
 
As far as I can tell, both your methods are thread safe. Remember that each
thread that accesses these methods pushes the parameters onto its own
individual stack which means each has its own copy.

Read the last message by Stephen Martin about thread safety of methods in
general:
http://www.dotnet247.com/247reference/msgs/29/149376.aspx

hopefully that should clear out any doubts you have regarding your methods.

hope that helps..
Imran.
 
Thanks for the article, it really helps clear it up for me. I was making
the INCORRECT assumption that if two threads called the same shared function
at the same time that the parameters to that function would also be shared
and that the last one in would when therefore making the method
thread-UNsafe.

Thanks again.
 
Back
Top