title: NET Core BackgroundService: "A task was canceled." Error
body: <p>Hello i developed BackgroundService which is to monitor Oracle Database and when new records inserted into source table, copy records into SQL Server Database. But after sometime (sometimes 1 days, sometimes 2 days). My service has stopped working. Error says: &quot;A Task was cancelled&quot;. I don't understand why my code has stopped working suddenly.</p>
  <p><strong>Note:</strong> my application hosting on IIS (Windows Server 2012)</p>
  <ul>
  <li>I want to run my application endlessly.</li>
  </ul>
  <p><strong>Here's my code:</strong></p>
  <pre><code>public class MainTransactionService : BackgroundService
      {   
      private readonly ILogger Logger;
      private readonly TransactionSettings TSettings;
      public MainTransactionService(ILogger logger, TransactionSettings tSettings)
      {
          TSettings = tSettings;
          Logger = logger;
      }
      protected async override Task ExecuteAsync(CancellationToken stoppingToken)
      {
          //Create a connection to Oracle         
          string conString = &quot;&quot;;
  
          //How to connect to an Oracle DB without SQL*Net configuration file
          //  also known as tnsnames.ora.
          //&quot;Data Source=orclpdb&quot;;
          &quot;Data Source=eoffice&quot;;
  
          OracleConfiguration.OracleDataSources.Add(&quot;eoffice&quot;, &quot;&quot;);
  
          //How to connect to an Oracle DB with a DB alias.
          //Uncomment below and comment above.
          //&quot;Data Source=&lt;service name alias&gt;;&quot;;
  
          OracleConnection con = new OracleConnection(conString);
          Logger.Information(&quot;Connected to Oracle&quot;);
          OracleCommand cmd = con.CreateCommand();
  
          try
          {
              Logger.Information(&quot;Run part executed&quot;);
  
              if (con.State != ConnectionState.Open)
              {
                  con.Open();
              }
              
              while (!stoppingToken.IsCancellationRequested)
              {
                  await Task.Delay(TSettings.Frequency, stoppingToken);
                  //Logger.Information(stoppingToken.IsCancellationRequested.ToString());
  
                  try
                  {
                      var cancelTask = Task.Delay(TSettings.Timeout, stoppingToken);
  
                      //Logger.Information(&quot;CODE EXECUTED&quot;);
                      //await context.Response.WriteAsync(&quot;Server is Listening&quot;);
  
                      //OracleConfiguration.OracleDataSources.Add(&quot;orclpdb&quot;, &quot;(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = miatdw1.miat.com.mn)(PORT = 1521)))(CONNECT_DATA = (SERVICE_NAME = orclpdb.miat.com.mn)))&quot;);
  
                      //Check Oracle
                      Logger.Information(&quot;Establishing Oracle Connection (While)&quot;);
                      cmd.CommandText = &quot;select MAX(id) from PB_TRANSACTION&quot;;
                      int SourceTableMaxId = Convert.ToInt32(cmd.ExecuteScalar());
  
                      //Check SQL
                      SqlConnection conn = new SqlConnection(&quot;&quot;);
                      SqlCommand check_id = new SqlCommand(&quot;select MAX(id) from PB_TRANSACTION&quot;, conn);
                      Logger.Information(&quot;Establishing MS-SQL Connection&quot;);
                      conn.Open();
                      int TargetTableMaxId = Convert.ToInt32(check_id.ExecuteScalar());
  
                      if (SourceTableMaxId &gt; TargetTableMaxId)
                      {
                          int TotalNewRecords = SourceTableMaxId - TargetTableMaxId;
  
                          Logger.Information(TotalNewRecords.ToString() + &quot; New Records Found&quot;);
  
  
                          OracleCommand command = new OracleCommand();
                          command.CommandText = &quot;select * from (select * from pb_transaction order by id desc) x where ROWNUM &lt;= :lastrecord&quot;;
                          command.Parameters.Add(&quot;:username&quot;, OracleDbType.Int32).Value = TotalNewRecords;
                          command.Connection = con;
  
                          Logger.Information(&quot;Retrieved &quot; + TotalNewRecords.ToString() + &quot; from PB_TRANSACTION table.&quot;);
  
                          Transaction LastTransaction = new Transaction();
  
                          using (OracleDataReader oReader = command.ExecuteReader())
                          {
                              while (oReader.Read())
                              {
                                  LastTransaction.Id = Convert.ToInt32(oReader[&quot;ID&quot;]);
                                  LastTransaction.type = oReader[&quot;TYPE&quot;].ToString();
                                  LastTransaction.account = oReader[&quot;ACCOUNT&quot;].ToString();
                                  LastTransaction.journal_id = oReader[&quot;JOURNAL_ID&quot;].ToString();
                                  LastTransaction.amount = Convert.ToDouble(oReader[&quot;AMOUNT&quot;]);
                                  LastTransaction.currency = oReader[&quot;CURRENCY&quot;].ToString();
                                  LastTransaction.posted_date = oReader[&quot;POSTED_DATE&quot;].ToString();
                                  LastTransaction.statement_date = oReader[&quot;STATEMENT_DATE&quot;].ToString();
                                  LastTransaction.description = oReader[&quot;DESCRIPTION&quot;].ToString();
                                  LastTransaction.pnr = oReader[&quot;PNR&quot;].ToString();
                                  LastTransaction.pnr_approved = Convert.ToInt32(oReader[&quot;PNR_APPROVED&quot;]);
                                  LastTransaction.jid = oReader[&quot;JID&quot;].ToString();
                                  LastTransaction.user_id = oReader[&quot;USER_ID&quot;].ToString();
                                  LastTransaction.inserted_date = oReader[&quot;INSERTED_DATE&quot;].ToString();
  
                                  SqlCommand scmd = new SqlCommand(&quot;insert into PB_TRANSACTION (ID,TYPE, ACCOUNT, JOURNAL_ID, AMOUNT, CURRENCY, POSTED_DATE, STATEMENT_DATE, DESCRIPTION, PNR, PNR_APPROVED, JID, USER_ID, INSERTED_DATE) values(@id,@type,@account,@journalid, @amount,@currency,@posteddate,@statementdate,@description,@pnr,@pnrapproved,@jid,@userid,@inserteddate);&quot;, conn);
                                  scmd.Parameters.AddWithValue(&quot;@id&quot;, LastTransaction.Id);
                                  scmd.Parameters.AddWithValue(&quot;@type&quot;, LastTransaction.type);
                                  scmd.Parameters.AddWithValue(&quot;@account&quot;, LastTransaction.account);
                                  scmd.Parameters.AddWithValue(&quot;@journalid&quot;, LastTransaction.journal_id);
                                  scmd.Parameters.AddWithValue(&quot;@amount&quot;, LastTransaction.amount);
                                  scmd.Parameters.AddWithValue(&quot;@currency&quot;, LastTransaction.currency);
                                  scmd.Parameters.AddWithValue(&quot;@posteddate&quot;, LastTransaction.posted_date);
                                  scmd.Parameters.AddWithValue(&quot;@statementdate&quot;, LastTransaction.statement_date);
                                  scmd.Parameters.AddWithValue(&quot;@description&quot;, LastTransaction.description);
                                  scmd.Parameters.AddWithValue(&quot;@pnr&quot;, LastTransaction.pnr);
                                  scmd.Parameters.AddWithValue(&quot;@pnrapproved&quot;, LastTransaction.pnr_approved);
                                  scmd.Parameters.AddWithValue(&quot;@jid&quot;, LastTransaction.jid);
                                  scmd.Parameters.AddWithValue(&quot;@userid&quot;, LastTransaction.user_id);
                                  scmd.Parameters.AddWithValue(&quot;@inserteddate&quot;, LastTransaction.inserted_date);
                                  scmd.ExecuteNonQuery();
                              }
                              Logger.Information(TotalNewRecords.ToString() + &quot; records inserted&quot;);
                          }
                      }
                      else
                      {
                          Logger.Information(&quot;No New Records found&quot;);
                      }
                  }
                  catch (Exception ex)
                  {
                      LogError(&quot;INNER TRY: &quot; + ex.Message);
                  }
              }
              Logger.Information(&quot;Oracle Database connection has successfully Disconnected!!!&quot;);
          }
          catch (TaskCanceledException tex)
          {
              LogError(&quot;TASK ERROR: &quot; + tex.Message);
          }
          catch (Exception ex)
          {
              LogError(&quot;MAIN ERROR: &quot; + ex.Message);
          }
          finally
          {
              con.Close();
              con.Dispose();
          }
      }
  
      public async override Task StopAsync(CancellationToken cancellationToken)
      {
          await base.StopAsync(cancellationToken);
      }
      private void LogError(string error)
      {
          Logger.Error(error);
      }
  } 
  </code></pre>