.net之ConcurrentQueue(Of T) VS List(Of T) 在多线程应用程序中使用 Synclock 语句

exmyth 阅读:12 2024-10-25 08:56:14 评论:0

我有一个 Public Shared queItems As Queue(Of String) 每当一个线程想要使用 Dequeue 删除并返回队列开头的字符串时,它就会被许多后台线程使用;

Public Function NextItem() As String 
    Dim _item As String = Nothing 
    SyncLock Form1.queItems 
        If Form1.queItems.Count = 0 Then Return Nothing 
        _item = Form1.queItems.Dequeue() 
        Form1.queItems.Enqueue(_item) 
    End SyncLock 
 
    Return _item 
End Function 

后来我被介绍给ConcurrentQueue(Of T) Class我使用 Public Shared queItems As ConcurrentQueue(Of String) 制作了下一个版本的 NextItem() As String,如下所示:

Public Function NextItem2() As String 
    Dim _item As String = Nothing 
here: 
    If Form1.queItems.Count = 0 Then Return Nothing 
    If Not Form1.queItems.TryDequeue(_item) Then 
        Thread.Sleep(100) 
        GoTo here 
    End If 
 
   Return _item 
End Function 

第一个版本在我的机器上比下一个版本快大约 20%。

但就线程安全性而言,它们是否等同?

最好使用哪个版本?

请您参考如下方法:

对于旧队列,你通常这样做(伪代码)

Public class SyncQueue 
 
    private _queue As new Queue(of String) 
    private shared _lock As New Object()  
 
    Public Shared Function Dequeue() As String 
 
        Dim item As String = Nothing 
        SyncLock _lock 
            If _queue.Count > 0 Then 
                _queue.Dequeue(item) 
            End If 
            Return item 
        End SyncLock 
    End Function 
 
    Public Shared Sub Enqueu(item as String) 
        SyncLock _lock 
            _queue.Enqueue(item) 
        End SyncLock 
    End Sub  
 
End Class 

使用 ConcurrentQueue(Of T) 时,所有这些都会为您处理。你应该使用 Try... 方法

If (queue.TryDequeue(item)) Then 
    ' do something with the item     
End If 


标签:多线程
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号