【发布时间】:2013-04-05 12:28:08
【问题描述】:
请帮我将以下循环转换为并行循环。我尝试使用 Parallel.ForEach 和 ConcurrentBag 而不是 HashSet,但奇怪的是“Matched”每次返回不同的结果。
我想不通...是不是因为线程安全问题?
关键字列表包含大约 500 个唯一字符串,每个字符串长度为 1-3 个单词。
Items 包含大约 10000 个项目。
原码:
Dim Items As IEnumerable(Of Item) = Db.Items.GetAll
Dim Keywords As HashSet(Of String)
Dim Matched As HashSet(Of Item)
For Each Item In Items
For Each Keyword In Keywords
If Regex.IsMatch(Headline, String.Format("\b{0}\b", Keyword), RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant) Then
If Not Matched.Contains(Item) Then
Matched.Add(Item)
End If
End If
Next
Next
尝试将其转换为
Dim Items As IEnumerable(Of Item) = Db.Items.GetAll
Dim Keywords As HashSet(Of String)
Dim Matched As Concurrent.ConcurrentBag(Of Item)
Threading.Tasks.Parallel.ForEach(Of Item)(Items, Sub(Item)
For Each Keyword In Keywords
If Regex.IsMatch(Item.Title, String.Format("\b{0}\b", Keyword), RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant) Then
If Not Matched.Contains(Item) Then
Matched.Add(Item)
End If
Continue For
End If
Next
End If
【问题讨论】:
标签: vb.net parallel-processing task-parallel-library parallel.foreach