Home > Back-end >  Asynchronous and Synchronous functions behavior in one blocking line
Asynchronous and Synchronous functions behavior in one blocking line

Time:09-17

I have this Synchronous function :

void AddItem(Item item)
{
    _context.Items.Add(item);
    _context.SaveChanges();
}

and the Asynchronous function :

async Task AddItemAsync(Item item)
{
    _context.Items.Add(item);
    await _context.SaveChangesAsync();
}

Do these functions have any difference at all ? I have a lot of functions like these in my project. just get an instance of an object, CRUD in database and return the result. Do I need to define my functions Asynchronous ? I saw a video that says Asynchronous programming is much better. I know if I have a blocking call and some independent work, it's better to use Asynchronous programming. But what about here ? And I must say that in the video he chooses to use code block 2nd.
Do I gain advantages from code block 2 ?

EDIT:

I know the pattern of async/await and its usage. My question is that both functions have similar behavior (not in thread pool) but is there any advantages that code block 2 has in this particular scenario ?

CodePudding user response:

When "SaveChangesAsync()" really starts a new task (i.e. with Task.Run()), code block 2 is asynchronous. But the task may be running in the UI-thread (main process thread), when he's free at the moment. That's why you see no used threadpool thread.

So code block 2 does not block the caller (calling thread) and returns immediately.

Regards

  • Related