I added the following extensions for my project to create a list of safe threads:
Extensions
If I want to perform 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 more than one parameter, I could just expand it with more elements ...
<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 created the following example actions:
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
as well as 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
Initiation
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 safe or do you have other recommendations? It is similar to the List.Foreach method, which performs an action.
user295190