线程安全,应用程序设计

时间:2011-07-25 15:13:16

标签: vb.net multithreading thread-safety console-application

我有一个控制台应用程序循环队列并处理数据表中的每个记录。每个过程都很耗时(连接到远程网站,下载文件,读取文件并将其添加到数据库中)。我试图为了速度而实现线程,但是我遇到了跨线程问题。 (该工作需要8个小时左右才能运行,并且跨线程直到运行几个小时才开始发生。)

我正在试图弄清楚如何使我的代码线程安全。我不更新或依赖任何非局部变量,我不需要返回任何东西。我试过锁定哪个有效,但是失败了多线程的目的。我应该寻找其他什么东西?

Module Module1

Dim iThread As Integer
Dim manualEvents(4) As ManualResetEvent
Private lockObject As New Object()

Sub Main()
    ' some prep work

    For i = 0 To 4
        manualEvents(i) = New ManualResetEvent(False)
        ThreadPool.QueueUserWorkItem(AddressOf DoOne)
    Next

    For Each handle As WaitHandle In manualEvents
        handle.WaitOne()
    Next

    ' some cleaning
End Sub


Private Sub DoOne()
    If QueryQueue Then
        DoOne()
    Else
        manualEvents(iThread).Set()
        iThread = iThread + 1
    End If
End Sub


Public Function QueryQueue() As Boolean

    Dim dt As DataTable = GetData()
    If dt.Rows.Count > 0 Then
        With dt
            Dim Variable1 As String = .Rows(0).Item("Variable1")
            Dim Variable2 As String = .Rows(0).Item("Variable2")
            Dim Variable3 As Integer = .Rows(0).Item("Variable3")
            ProcessRecord(Variable1, Variable2, Variable3)
        End With
        Return True
    Else
        Return False
    End If

End Function

Public Sub ProcessRecord(ByVal Variable1 As String, ByVal Variable2 As String, ByVal Variable3 As Integer)
    AnotherMethod(Variable1, Variable2, Variable3)
End Sub

Public Sub AnotherMethod(ByVal Variable1 As String, ByVal Variable2 As String, ByVal Variable3 As Integer)
    AnotherMethod2(Variable1, Variable2, Variable3)
End Sub

Public Sub AnotherMethod2(ByVal Variable1 As String, ByVal Variable2 As String, ByVal Variable3 As Integer)
    AnotherMethod3(Variable1, Variable2, Variable3)
End Sub

' ... etc.

End Module

1 个答案:

答案 0 :(得分:0)

iThread = iThread + 1不是线程安全的 您应该拨打Interlocked.Increment

如果您使用的是.Net 4.0,则应使用新的Task API而不是ThreadPool;然后,您可以拨打Task.WaitAll