Home > Enterprise >  Use multithreading in .net webapi
Use multithreading in .net webapi

Time:11-21

In my dot net core web api, I know the number of cpu thread available and the number of data to be processed. Lets say I have 8 threads for 800 data update request. How can I do something so that each thread handles 100 data update request in parallel?

(I am completely new in .NET core multi threading and would like to have a tutorial link for beginner if you don't want to share code.)

Here is my code:

[HttpPatch("UpdateExams")]
public async Task < ActionResult < ResponseDto2 >> UpdateExam([FromBody] List < Exam > input) {
    // I know the number of threads -- lets say 8
    int tc = Process.GetCurrentProcess().Threads.Count;
    // I know the number of inputs -- lets say 800
    int ic = input.Count;
    // how can I distribute 100 data update request per core so that they run parallelly ?
    // note: it is an data update operation

    // below is my current api code
    using
    var transaction = _context.Database.BeginTransaction();
    try {

        foreach(var item in input) {
            Exam exam = await _context.Exams.Where(i => i.FormNo == item.FormNo && i.RegNo == item.RegNo).FirstOrDefaultAsync();
            if (exam != null) {
                exam.ExamRollno = item.ExamRollno;
                _context.Exams.Update(exam);
                await _context.SaveChangesAsync();
            }
        }
        transaction.Commit();
    } catch (Exception e) {
        return StatusCode(StatusCodes.Status500InternalServerError, new ResponseDto2 {
            Message = "Something went wrong. Please try again later",
                Success = false,
                Payload = new {
                    e.StackTrace,
                        e.Message,
                        e.InnerException,
                        e.Source,
                        e.Data
                }
        });
    }
    return StatusCode(StatusCodes.Status200OK, new ResponseDto2 {
        Message = "Data Updated successfully",
            Success = true,
            Payload = null
    });
}

CodePudding user response:

Stop thinking in threads. Sure, a CPU has "cores" and "threads", but some of those rather do other things than service your application, like keeping the OS functional and have your web server respond to other requests.

I could link to the Task Parallel Library, but you commented that you don't want any MS Docs links.

Then I'll address what you're actually doing: you're doing a bulk import with Entity Framework and calling SaveChanges() for every entity. No amount of parallelization is going to help in optimizing that.

There are libraries to do bulk imports in SQL without the Entity Framework overhead.

  • Related