Search code examples
.netmultithreadinginfinite-loopcancellationtokensource

.NET How to keep a Threading.Task alive with a While Loop


I have no previous experience with Windows's DebugDiag and need some insight about this report.

My EWS Managed API application spans a new task evertytime an event occurs.

My app runs on ~30-35% CPU usage so I decided to run this diagnostic tool to find out the wheres and whys.

I got this and need to make sure what I see is right what I think it is.

Judging from the picture below it says that the Task.StartNew function was executed 5 times and that caused this high CPU usage?

Update

After looking deeper I found what appears to be the "Stacktrace" with some function calls highlighted in Red, I have a feeling red means these functions cause the high CPU, and these functions appear to be comming from EWS Managed API code.

Analysis Report

enter image description here


Solution

  • I found the CPU eating piece of code.

    I had an infinite while loop inside the Tast because I needed to keep it from being garbage collected.

            While Not pToken.IsCancellationRequested
                If pToken.IsCancellationRequested Then Return
            End While
    

    This caused my CPU usage to go high 38% all the time!

    So instead I used

            _CancelSignal = New AutoResetEvent(False)
    
            _CancelSignal.WaitOne()
    

    To put the thread to sleep until I tell it to exit by setting the _CancelSignsal