Multithreaded Access - ReaderWriterLock

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a public shared property in global.asax.

When the variable of the property is not instantiated (first page to call
it, cache empties, etc.) the code then loads the variable from source (web
service, database, file, etc.)

What I want to do is prevent many simultaneous users access this property
when it's variable is not instantiated and have all of them go to the source.

I have this following property that uses locks but all of the concurrent
users still end up calling the source. I am not sure what I am missing.

Public Shared ReadOnly Property ConcurrencyChecking() As String
Get
Dim rwl As ReaderWriterLock
Dim lockThreadCookie As LockCookie

rwl = New ReaderWriterLock
Try
'Everyone gets a reader lock
rwl.AcquireReaderLock(100)

If _hello Is Nothing Then

Dim WebService As TestConcurrency.WebService.BusinessLayer

'Upgrade to writer lock
Dim sequenceNum As Integer = rwl.WriterSeqNum
lockThreadCookie = rwl.UpgradeToWriterLock(100)
Try
'Call the Web Service <- only want the first concurrent
user to do this
If rwl.AnyWritersSince(sequenceNum) = False Then
WebService = New
TestConcurrency.WebService.BusinessLayer
'Sleeps for eight seconds
_hello = WebService.HelloWorld2(8000)
End If
Finally
rwl.ReleaseWriterLock()
End Try
End If
Finally
rwl.ReleaseLock()
End Try

Return _hello

End Get
End Property


Thanks!
Fm
 
Hi

From your code, it seems that every user access the property will create a
new ReaderWriterLock.
You may take a look at the link below.
ReaderWriterLock Class
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemthreadingreaderwriterlockclasstopic.asp

You may try to decare the ReaderWriterLock in the class level, e.g. the
Global class's static variable, so that we can make sure that every user
will operation on the same lock.

You may have a try and let me know the result.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top