E
Eduardo Garcia-Prieto
I have come accross a problem in using the
Interlocked.Exchange(Object, Object) method while using Option Strict
On in my project. I have a private class structure variable which can
be updated by a separate thread. In order to guarantee that the
variable can be updated in an atomic operation it occurred to me that
I could use Interlocked.Exchange.
Class MyClass
Private Structure MyStructure
Dim Value As String
End Structure
Private _myStruct As MyStructure
Public ReadOnly Property Value As String
Get
Return _myStruct.Value
End Get
End Property
'Method that can be called by another thread
Public Sub UpdateMyStruct()
Dim NewStruct As MyStructure
NewStruct.Value = "B"
Interlocked.Exchange(_myStruct, NewStruct)
End Sub
End MyClass
The problem is that when Option Strict is On, the compiler issues a
build error on the line with the call to
Interlocked.Exchange(_myStruct, NewStruct):
....
Overload resolution failed because no accessible 'Exchange' can be
called with these arguments:
'Public Shared Function Exchange(ByRef location1 As Object, value
As Object) As Object':
Option Strict On disallows implicit conversions from 'System.Object'
to 'MyNamespace.MyClass.MyStructure'.
....
To work around it I have implemented a ReaderWriterLock in the class
to synchronise access to the private structure variable.
Has anyone dealt with this situation in a better way? I don't want to
turn Option Strict off.
Interlocked.Exchange(Object, Object) method while using Option Strict
On in my project. I have a private class structure variable which can
be updated by a separate thread. In order to guarantee that the
variable can be updated in an atomic operation it occurred to me that
I could use Interlocked.Exchange.
Class MyClass
Private Structure MyStructure
Dim Value As String
End Structure
Private _myStruct As MyStructure
Public ReadOnly Property Value As String
Get
Return _myStruct.Value
End Get
End Property
'Method that can be called by another thread
Public Sub UpdateMyStruct()
Dim NewStruct As MyStructure
NewStruct.Value = "B"
Interlocked.Exchange(_myStruct, NewStruct)
End Sub
End MyClass
The problem is that when Option Strict is On, the compiler issues a
build error on the line with the call to
Interlocked.Exchange(_myStruct, NewStruct):
....
Overload resolution failed because no accessible 'Exchange' can be
called with these arguments:
'Public Shared Function Exchange(ByRef location1 As Object, value
As Object) As Object':
Option Strict On disallows implicit conversions from 'System.Object'
to 'MyNamespace.MyClass.MyStructure'.
....
To work around it I have implemented a ReaderWriterLock in the class
to synchronise access to the private structure variable.
Has anyone dealt with this situation in a better way? I don't want to
turn Option Strict off.