gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:35:08 25 4
gpt4 key购买 nike

在下面的示例代码中,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com