VB.net:我的线程安全列表解决方案真的安全吗?
我已将以下扩展添加到我的项目中,以便创建线程安全列表:
扩展 如果我想在我的列表上进行一项简单的操作
<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
如果我想传递多个参数,我可以简单地用更多项目扩展它...
<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
操作 我创建了以下操作示例:
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
还有一个带有参数的操作示例:
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
启动 然后在我的各种线程中,我将使用以下方式调用我的操作:
list.Action(AddressOf Read)
或者
list.Action(AddressOf Write2, 10)
这些扩展方法线程安全吗?或者您有其他建议吗?它类似于执行操作的 List.Foreach 方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它们看起来是线程安全的。但只有正确使用时,这可能会变得难以管理。您必须非常小心地观察死锁情况。
有“最佳实践”指出您不应该锁定列表本身(因为其他代码也可能如此),但您违反了该建议。在实践中这并不是一个迫在眉睫的问题,而是潜伏在阴影中等待不太可能发生的巧合的事情。
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.