1

I am implementing method for seeding data (and calling it in Startup.Configure() method) which looks like

if(!_context.Table.Any()) 
{
   _context.Table.Add();
   _context.SaveChanges();
}

And I want to make it async using Task, so I changed my code to this

Task.Run(async () =>
{
   if(! await _context.Table.AnyAsync()) 
   {
      await _context.Table.AddAsync();
      await _context.SaveChangesAsync();
   }
});

But It didn't work. So I add Wait() to the Task.Run() and method started working.

Task.Run(async () =>
{
   if(! await _context.Table.AnyAsync()) 
   {
      await _context.Table.AddAsync();
      await _context.SaveChangesAsync();
   }
}).Wait();

So, are there any differences between first and last parts of code?

As I know, Wait() method blocks the thread, so are these parts of code the same?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Roomey
  • 716
  • 2
  • 9
  • 16
  • 1
    `Task.Run` = "I need this code to run somewhere else, *this* thread has got other work to do" - `.Wait` = "This thread cannot do anything useful until this other thing has finished". How do you think using them both together makes sense? – Damien_The_Unbeliever Sep 09 '21 at 07:41
  • 1
    "*But it didn't work.*" what was the problem? – Theodor Zoulias Sep 09 '21 at 08:48
  • @Damien_The_Unbeliever I'd say it makes (some) sense in legacy code when (1) this thread has to orcestrate multiple tasks before it waits for all of them or (2) the called async method with poor implementation needs to be embedded in a sync context without deadlocking. So basically, don't write new code that sync-waits for no reason, but don't waste years just to avoid such code, when dealing with legacy. – grek40 Sep 09 '21 at 10:34

0 Answers0