Thread sync problem

  • Thread starter Thread starter Gordon Knote
  • Start date Start date
G

Gordon Knote

Hi

I'm currently writing a VB.NET service that uses external
Dlls, like this:

Private Declare Function ReadSettings Lib "mydll.dll" ()

Now, how can I protect this function (ReadSettings) from
being called more then once a time?
I tried to use

System.Threading.Monitor.Enter(ReadSettings)
ReadSettings()
System.Threading.Monitor.Exit(ReadSettings)

but this caused a reference null exception. So, can
anyone tell me how I can protect external functions?


Thanks
Gordon
 
Gordon said:
Hi

I'm currently writing a VB.NET service that uses external
Dlls, like this:

Private Declare Function ReadSettings Lib "mydll.dll" ()

Now, how can I protect this function (ReadSettings) from
being called more then once a time?
I tried to use

System.Threading.Monitor.Enter(ReadSettings)
ReadSettings()
System.Threading.Monitor.Exit(ReadSettings)

but this caused a reference null exception. So, can
anyone tell me how I can protect external functions?


Thanks
Gordon

You need to use an object in your Monitor.Enter. So you would do
something like this...

Public Class Resource

Private Object lockObject = New Object()


Public Function ThisIsTheFunction() As Integer
Try
Monitor.Enter(lockObject)
ReadSettings()
Catch (Exception ex)
' Handle your exceptions
Finally
Monitor.Exit(lockObject)
End Try
End Function

End Class

You can also use SyncLock as well. It is really just a shorthand for
using the Monitor object and the Try/Catch/Finally stuff ;)

HTH,
Tom Shelton
 
You can also use SyncLock as well. It is really just a shorthand for
using the Monitor object and the Try/Catch/Finally stuff ;)

Which would become...

' ///
Public Class Resource

Private lockObject As New Object

Public Function ThisIsTheFunction() As Integer

SyncLock lockObject
ReadSettings()
End SyncLock

End Function

End Class
' ///

--
HTH,
-- Tom Spink, Über Geek

Please respond to the newsgroup,
so all can benefit

"Maybe it's a game called 'Punish the User'"
 
Back
Top