VB.net: Is my Thread Safe List Solution actually safe?
- by Shiftbit
I've added teh following Extensions to my Project in order to create a thread safe list:
Extensions
If I want to conduct a simple operation on my list
<Extension()> _
Public Sub Action(Of T)(ByVal list As List(Of T), ByVal action As Action(Of List(Of T)))
SyncLock (list)
action(list)
End SyncLock
End Sub
If I want to pass it more than one parameter I could simply extend it with more items...
<Extension()> _
Public Sub Action(Of T)(ByVal list As List(Of T), ByVal action As Action(Of List(Of T), T), ByVal item As T)
SyncLock (list)
Action(list, item)
End SyncLock
End Sub
Actions
I have created the following Action Examples:
Private Sub Read(Of T)(ByVal list As List(Of T))
Console.WriteLine("Read")
For Each item As T In list
Console.WriteLine(item.ToString)
Thread.Sleep(10)
Next
End Sub
and also one that takes a parameter:
Private Sub Write(Of T)(ByVal list As List(Of T), ByVal item As T)
Thread.Sleep(100)
list.Add(item)
Console.WriteLine("Write")
End Sub
Initiating
Then in my various threads I will call my Actions with:
list.Action(AddressOf Read)
or
list.Action(AddressOf Write2, 10)
Are these Extenxion methods thread safe or do you have other recommendations?