문제

Below, you will find the source of my latest coding heartache. It is a small method in a base class that runs methods of derived classes in a secondary thread. This code runs about 5 times in a windows service that kicks off every 5 minutes.

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

It will run fine for some time. Eventually it runs out of memory. From that point forward, memory errors are thrown until the service is restarted. The text of an actual thrown error is as follows:

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();

These errors didn't really start happening until I started using an AutoResetEvent to control my while loop. I use to use System.Threading.Thread.Sleep. However, one of the com objects I call wouldn't ever run when I used the sleep method. Changing to AutoResetEvent got that code to run, but the memory errors are now showing up even if the method that calls the com object is not one of the derived classes to run.

Please help. :)

도움이 되었습니까?

해결책

Going back to system.threading.thread.sleep solved my problem. Only the device that needs the AutoResetEvent to work is using AutoResetEvent . The memory erorrs have gone way.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top