下面,您将找到我最新的编码心痛的来源。它是基类中的一个小方法,在辅助线程中运行派生类的方法。此代码在每 5 分钟启动一次的 Windows 服务中运行大约 5 次。
Private Sub performAction(ByVal startedAt As DateTime)
Dim waiter As New System.Threading.AutoResetEvent(False)
Try
Dim statusTimeout As Short = DefaultTimeOutSeconds
Dim action As Threading.Thread = New Threading.Thread(AddressOf ActionToPerform)
Dim configHelper As New ApplicationHelper.SST_CONFIG()
Short.TryParse(configHelper.GetConfig(String.Format("{0}.Timeout", ActorType), DefaultTimeOutSeconds), statusTimeout)
action.SetApartmentState(System.Threading.ApartmentState.STA)
action.Priority = Threading.ThreadPriority.Highest
action.Start()
While LastUpdated < startedAt AndAlso DateTime.Now <= startedAt.AddSeconds(statusTimeout)
waiter.WaitOne(1000)
End While
Finally
waiter.Close()
End Try
End Sub
它会运行一段时间。最终它会耗尽内存。从那时起,将引发内存错误,直到服务重新启动。实际抛出的错误的文本如下:
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Threading.WaitHandle.WaitOneNative(SafeHandle waitableSafeHandle, UInt32 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.InternalWaitOne(SafeHandle waitableSafeHandle, Int64 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.WaitOne(Int32 millisecondsTimeout, Boolean exitContext)
at System.Threading.WaitHandle.WaitOne(Int32 millisecondsTimeout)
at DeviceManagement.AsynchronousDeviceAction.performAction(Thread& action, DateTime startedAt)
at DeviceManagement.AsynchronousDeviceAction.Perform()
at DeviceManagement.PAJournalPrinter.GetStatus();
直到我开始使用 AutoResetEvent 来控制我的 while 循环,这些错误才真正开始发生。我曾经使用 System.Threading.Thread.Sleep。但是,当我使用 sleep 方法时,我调用的 com 对象之一永远不会运行。更改为 AutoResetEvent 可以运行该代码,但是即使调用 com 对象的方法不是要运行的派生类之一,现在也会显示内存错误。
请帮忙。:)