使用多个线程访问变量的正确方法

时间:2014-02-24 17:37:57

标签: vb.net multithreading

在将被其他线程修改的表单中声明和访问变量的正确方法是什么?看起来如果你只是正确维护类的一个实例并通过引用将其传递到任何地方,所有线程都将访问同一个变量。这样做的正确方法是什么?我是否应该始终将变量封装在各自的类中?

方法1:

Public Class frmMain

    Private _emailsync As New Object
    Public _lastemail As Date

    Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        _lastemail = New Date(1970, 1, 1)
    End Sub

    Public Sub SendEmail() 'CalledFromAnotherThread
        If Now().Subtract(_lastemail).TotalHours > 3 Then
            SyncLock _emailsync
                _lastemail = Now()
            End SyncLock
            'MailMessage code here
        End If
    End Sub

End Class

方法2:

Public Class frmMain

    Private _emailsync As New Object
    Private _vars As Vars

    Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        _vars = New Vars()
    End Sub

    Public Sub SendEmail() 'CalledFromAnotherThread
        If Now().Subtract(_vars._lastemail).TotalHours > 3 Then
            SyncLock _emailsync
                _vars._lastemail = Now()
            End SyncLock
            'MailMessage code here
        End If
    End Sub

    Private Class Vars
        Public _lastemail As Date

        Sub New()
            _lastemail = New Date(1970, 1, 1)
        End Sub
    End Class

End Class

0 个答案:

没有答案