Search code examples
multithreadingasp.net-coreasp.net-core-mvcasp.net-core-webapibackground-service

Insert bulk data in background in .Net Core


I'm using .Net Core 3.1 and I want to insert bulk data in the background, so I don't need my http request waiting for it "like fire and forget"

So I tried the following code

public object myFunction(){
    Task.Factor.StartNew(() => {
        _context.BulkInsertAsync(logs);
    });

    return data;
}

But nothing is happend, no data saved in database is after my data returned my _context and logs will be null, so the process is filed? or there is any another method to insert my data and don't wait for it

Note: the background task working if I replace insertion statment with sending mail or any other thing

Solved:

Thanks @Peter , I solved it using

Task.Run(async () => await _context.BulkInsertAsync(logs));

Solution

  • Task.Factory.StartNew or TaskFactory.StartNew cannot accept async delegates (Func<Task>), so you should use Task.Run instead which is indeed has an overload with Func < Task >. You would have to use await await or Unwrap against StartNew to get the same behaviour as with Run. Please read Stephen Toub's excellent blog post.

    public object myFunction(){
        Task.Run(async () => await _context.BulkInsertAsync(logs));
        return data;
    }