views:

103

answers:

1

I've added the 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? It is similar to the List.Foreach method which takes an action.

+1  A: 

Yes, they look thread-safe. But only when used correctly, and that might become hard to manage. You will have to watch real careful for deadlock situations.

There is 'best practice' stating you shouldn't lock on the list itself (because other code might as well) and you break that advice. Not an immediate problem in practice, but something lurking in the shadows waiting for an unlikely coincidence to happen.

Henk Holterman