title: What can I do about Azure Function leaking memory via CancellationTokenSource?
body: <p>I'm analyzing the memory usage of Azure Functions under load test. When I run the template function with an HTTP trigger:</p>
  <pre><code>using System;
  using System.IO;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Azure.WebJobs;
  using Microsoft.Azure.WebJobs.Extensions.Http;
  using Microsoft.AspNetCore.Http;
  using Microsoft.Extensions.Logging;
  using Newtonsoft.Json;
  
  namespace TestFunction
  {
      public static class Function1
      {
          [FunctionName(&quot;Function1&quot;)]
          public static async Task&lt;IActionResult&gt; Run(
              [HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,
              ILogger log)
          {
              log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);
  
              string name = req.Query[&quot;name&quot;];
  
              string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
              dynamic data = JsonConvert.DeserializeObject(requestBody);
              name = name ?? data?.name;
  
              string responseMessage = string.IsNullOrEmpty(name)
                  ? &quot;This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.&quot;
                  : $&quot;Hello, {name}. This HTTP triggered function executed successfully.&quot;;
  
              return new OkObjectResult(responseMessage);
          }
      }
  }
  </code></pre>
  <p>and test it by firing 100,000 HTTP calls at it in 10 parallel threads, from another Visual Studio instance:</p>
  <pre><code>using Microsoft.Extensions.Logging;
  using NUnit.Framework;
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Net.Http;
  using System.Threading.Tasks;
  
  namespace TestProject1
  {
      public class Tests
      {
          [Test]
          public async Task TestQueryFunction()
          {
              var url = &quot;http://localhost:7071/api/Function1&quot;; // &quot;http://localhost:7071/api/GetTaskLogs?subscription-key=471f69529605476990ab8c074de44f9a&amp;oil-tenant-id=testsuite-acc&amp;ExternalID=IVQ20&quot;;
              var tasks = new List&lt;Task&gt;();
              for (int i = 0; i &lt; 10; i++)
              {
                  var threadNumber = i;
                  tasks.Add(Task.Run(async () =&gt; {
                      await Task.Delay(threadNumber * 100);
                      var stopwatch = new Stopwatch();
                      for (int j = 0; j &lt; 10000; j++)
                      {
                          stopwatch.Restart();
                          var response = await httpClient.GetAsync(url);
                          Debug.WriteLine(threadNumber + &quot;, &quot; + j + &quot;: &quot; + stopwatch.ElapsedMilliseconds);
                      }
                  }));
              }
              await Task.WhenAll(tasks);
          }
  
          private static readonly HttpClient httpClient = new HttpClient();
      }
  }
  </code></pre>
  <p>the memory usage of the Function has increased from 74MB (after startup) to 214MB. According to the snapshot, a lot of memory is tied to <code>CancellationTokenSource</code> which I don't use, at least not explicitly:</p>
  <p><a href="https://i.stack.imgur.com/TnSNy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TnSNy.jpg" alt="enter image description here" /></a></p>
  <p>How can I prevent this? I found a related GitHub issue <a href="https://github.com/Azure/azure-functions-servicebus-extension/issues/104" rel="nofollow noreferrer">CancellationTokenSource is not disposed in ServiceBusListener.ProcessMessageAsync and ServiceBusListener.ProcessSessionMessageAsync (possible memory leak)</a> but that's for Service Bus triggers and that has been fixed.</p>
  <p>I'm using Visual Studio 2022, .NET Core 6 and Functions SDK 4.0.1, but I was also able to reproduce it in VS2019, .NET Core 3.1 and Functions SDK 3.0.13.</p>