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

标签 c# .net vb.net multithreading

在下面的示例代码中,timer elapsed 事件将始终在后台线程或主线程上运行吗?

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

最佳答案

它也不会运行。它将在随机线程池线程上运行,除非您指定一个 SynchronizingObject 来将调用编码到另一个线程。

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

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

关于c# - .Net 类中的代码是否总是在创建它的线程上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38342190/

相关文章:

C# OOPS 说明

c# - 如何防止回到上一页

c# - WPF上下文菜单,复制菜单项变灰

c# - 使用 OpenSSL .Net 检索证书

c# - 二进制排序逻辑 : not sorting numbers correctly

c# - 要让我的网站在移动浏览器上运行,我需要知道什么?

c# - try catch 和 finally block 的执行顺序

vb.net - 两个应用程序之间的序列化

c# - 是否可以使用 TagLibSharp 从 MP3 文件中删除 Lyrics3v2 标签?

asp.net - 如何让函数在 VB.net 中运行回调