1

Hello My Program got this error and i dont know why?

Since 'InsertToHomeSecondPagesTableJob.Execute(IJobExecutionContext)' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task'?

this is my code

   public async Task Execute(IJobExecutionContext context)
        {
            var PagesScoreNewsHomePageTable = new PagesScoreNewsHomePageTable()
            {
             PagesID = 1,
             UserID = 22,
             Author = "jack"
            };                              
        _db.AddAsync(PagesScoreNewsHomePageTable);
        _db.SaveChangesAsync();
        
        return Task.CompletedTask;
 }

how can i solve this error?

  • Does this answer your question? [What do I return from a method that returns just Task and not Task?](https://stackoverflow.com/questions/37646858/what-do-i-return-from-a-method-that-returns-just-task-and-not-taskt) – Dimitris Maragkos Oct 03 '22 at 09:43
  • Do you intend to fire-and-forget the save changes call? Since currently it is not awaited. – juunas Oct 03 '22 at 10:23

1 Answers1

1

The simple and recommended way to solve this problem is using await keywords.

The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in .NET Framework, .NET Core, or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method.

You just need to change your code like:

public async Task Execute(IJobExecutionContext context)
        {
            var PagesScoreNewsHomePageTable = new PagesScoreNewsHomePageTable()
            {
             PagesID = 1,
             UserID = 22,
             Author = "jack"
            };                              
       await _db.AddAsync(PagesScoreNewsHomePageTable);
       await _db.SaveChangesAsync();
        
 }

More details about async you can refer to this Docs.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12