title: Cannot access a disposed object in Task.Run
body: <p>I am using <strong>.NET Core 3.1</strong>. I want to run some background processing without user having to wait for it to finish (it takes about 1 minute). Therefore, I used <code>Task.Run</code> like this:</p>
  
  <pre><code>public class MyController : Controller
  {
      private readonly IMyService _myService;
  
      public MyController(IMyService myService)
      {
          _myService = myService;
      }
  
      public async Task&lt;IActionResult&gt; Create(...)
      {
          await _myService.CreatePostAsync(...);
          return View();
      }
  }
  
  public class MyService : IMyService
  {
      private readonly MyDbContext _dbContext;
      private readonly IServiceScopeFactory _scopeFactory;
  
      public MyService(MyDbContext dbContext, IServiceScopeFactory scopeFactory)
      {
          _dbContext = dbContext;
          _scopeFactory = scopeFactory;
      }
  
      public async Task CreatePostAsync(Post post)
      {
          ...
          string username = GetUsername();
          DbContextOptions&lt;MyDbContext&gt; dbOptions = GetDbOptions();
          Task.Run(() =&gt; SaveFiles(username, dbOptions, _scopeFactory));
      }
  
      private void SaveFiles(string username, DbContextOptions&lt;MyDbContext&gt; dbOptions, IServiceScopeFactory scopeFactory)
      {
          using (var scope = scopeFactory.CreateScope())
          {
              var otherService = scope.ServiceProvider.GetRequiredService&lt;IOtherService&gt;();
              var cntxt = new MyDbContext(dbOptions, username);
  
              Post post = new Post("abc", username);
  
              cntxt.Post.Add(post); &lt;----- EXCEPTION
  
              cntxt.SaveChanges();
          }
      }
  }
  </code></pre>
  
  <p>I recieve the following exception in marked line:</p>
  
  <pre><code>System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'IServiceProvider'.'
  </code></pre>
  
  <p>Why does this happen? I used custom constructor (and not <code>scope.ServiceProvider.GetRequiredService&lt;MyDbContext&gt;()</code>) for MyDbContext because I need to save one additional propery (username) for later use in overriden methods.</p>
  
  <pre><code>public partial class MyDbContext
  {
      private string _username;
      private readonly DbContextOptions&lt;MyDbContext&gt; _options;
  
      public DbContextOptions&lt;MyDbContext&gt; DbOptions { get { return _options; } }
  
      public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options, string username) : base(options)
      {
          _username = username;
          _options = options;
      }
  
      ... other overriden methods
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>