【问题标题】:Parallel Loop & Stringbuilder并行循环和字符串生成器
【发布时间】:2016-09-28 12:05:56
【问题描述】:

简介:大家好,这是我的第一个问题,所以如果我做错了或做错了什么,请告诉我。我正在做一个项目,它的一个功能是编写大量文本来处理数据并在某些行替换特定文本并将文件输出到 Richtextbox/文件。

问题:问题是当我使用并行foreach时,我在richtextbox中的结果到处都是,它们不是按行(例如第一行可能在并行foreach循环运行后变成第15行) )。

代码的作用:它循环通过一个富文本框并检查该行是否与临时富文本框中的第一行匹配,如果是,它将停止附加并从临时富文本框中复制文本并让循环运行直到数量过去的行数与临时富文本框中的行数相匹配,然后继续追加。它基本上是文本的替换。我正在查看大约 20K 行的总输出。

Dim completertb4text As New StringBuilder("")

Parallel.ForEach(newrtb.Lines, Function() New StringBuilder(), Function(x, [option], sb)

If x.Contains(richtextboxl0) Then
  startcount = True
  sb.Append(vbNewLine & richtextbox3text & "111111")
End If

If startcount = True Then
  If counter = temptextbox3count Then
     startcount = False
  Else
     counter += 1
  End If
End If

If sb.Length = 0 Then
  sb.Append(vbNewLine & x & "222222")
End If

If sb.Length > 0 Then
  sb.Append(vbNewLine & x & "3333333")
End If
Return sb

Function, Sub(sb)     
  SyncLock completertb4text
    completertb4text.Append(sb.ToString())
  End SyncLock
End Sub

任何帮助都非常感谢,在此先感谢!

【问题讨论】:

  • 不确定我是否正确理解了您的问题...从您的代码看起来,1. 读取富文本框中的内容,2. 如果 RTB 中的某些文本出现在某些 TextBox 中,请将其替换by something 3. 在其他 RTB 中写入更新的内容。对吗???
  • 是的,先生,您是对的。
  • 恐怕你将能够通过使用 Parallel.ForEach 实现你想要的
  • 我想你的意思是我无法做到这一点,那么还有其他方法可以重构我的代码吗?我刚刚开始学习代码优化,所以我对这个并行的东西还很陌生。非常感谢您的帮助。

标签: vb.net visual-studio-2015 parallel.foreach


【解决方案1】:

这是我将代码从 08:00 秒缩短到 00:01 秒的方法。

            Dim counter As Integer = 0
        Dim countertrue As Integer = 0
        Dim countintertal As Integer = 0


        Dim newrtbstrarray As String() = newrtb.Lines
        Dim rtb3array As String() = richtextbox3text.Lines

        For Each line As String In newrtbstrarray

            If line.Contains(richtextboxl0) Then
                countertrue = counter
                For Each element As String In rtb3array
                    newrtbstrarray(countertrue) = rtb3array(countintertal)
                    countertrue += 1
                    countintertal += 1
                Next

            End If

            counter += 1
        Next

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多