.Net类中的代码是否总是在创建它的线程上运行?

时间:2016-07-13 03:26:25

标签: c# .net vb.net multithreading

在下面的示例代码中,定时器已用事件是否总是在后台线程或主线程上运行?

Public Class MainClass    
    Dim SomeSubClassInstance As SomeSubClass

    Public Sub New()
        'Create a thread which will then create an instance of the sub class
        Dim T As New Threading.Thread(AddressOf CreateSomeSubClass)
        T.IsBackground = True
        T.Start()
    End Sub

    Private Sub CreateSomeSubClass()
        'This code runs on the background thread, and creates the instance of SomeSubClass
        SomeSubClassInstance = New SomeSubClass
    End Sub

    Public Class SomeSubClass
        Dim WithEvents tmrDoWork As Timers.Timer
        Public Sub New()
            tmrDoWork = New Timer
            tmrDoWork.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds
            tmrDoWork.Start()
        End Sub

        Private Sub tmrDoWork_Elapsed(sender As Object, e As ElapsedEventArgs) Handles tmrDoWork.Elapsed
            'Will this code be run on the background thread that was created in the MainClass constructor?
        End Sub
    End Class
End Class

1 个答案:

答案 0 :(得分:4)

它不会在任何一个上运行。它将在随机线程池线程上运行,除非您指定一个SynchronizingObject,它将封送对另一个线程的调用。

如果SynchronizingObject属性为null,则在ThreadPool线程上引发Elapsed事件。如果Elapsed事件的处理持续时间超过Interval,则可能会在另一个ThreadPool线程上再次引发该事件。在这种情况下,事件处理程序应该是可重入的。

https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx