title: Start multiple background threads inside Self Hosted ASP.NET Core Microservice
body: <p>Where can i create multiple long running background threads in <code>Self Hosted Self Contained ASP.NET Core Microservice</code> whose lifetime is same as micro-service lifetime? So that information retrieved from threads can be sent as a response to the requests.</p>
  
  <p>Tried given code but it reduces http request performance when background threads are busy. Main method of Program.cs file is:</p>
  
  <pre><code>static void Main(string[] args)
  {
      //Start background thread1
      //Start background thread2
      //Around 10 background threads
      //Start host
      var host = new WebHostBuilder()
          .UseKestrel()
          .UseUrls(ServerUrl)
          .UseConfiguration(config)
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .ConfigureServices(s =&gt; s.AddRouting())
          .Configure(app =&gt; app.UseRouter(r =&gt; { (new Router()).Route(r); }))
          .Build();
      host.Run();
  }
  </code></pre>
  
  <p>Threads work in this way:</p>
  
  <pre><code>Thread t1 = new Thread(StartWork);
  t1.IsBackground = true;
  t1.Start();
  
  public void StartWork()
  {
      while (ApplicationIsRunning)
      {
          //Get database info &gt;&gt; login into remote devices (SSH) &gt;&gt; get information &gt;&gt; process information &gt;&gt; update application variables and database
          Thread.Sleep(10000);
      }
  }
  </code></pre>
  
  <p>CPU utilization is only 1-5% when threads are busy but still http request performance is very bad. After going to sleep state performance again improves.</p>
  
  <p>The issue is at connect method of SSH client connection. At some point connect method is not responding and it affect all other threads also. That is strange!</p>
  
  <pre><code>Renci.SshNet.SshClient sshClient = New Renci.SshNet.SshClient(sshConnectionInfo);
  sshClient.Connect();
  </code></pre>
  
  <p>If one thread is busy in connection because of any reason it should not affect other threads.</p>