async without await

winanjaya 146 Reputation points
2023-02-07T12:11:55.0733333+00:00

Hi All,

I need clarification for my understanding about async below:

  • we don't have to always use await in async if we don't need to await for the result of the process, please CMIIW

below codes, will run async without await, it will continues to return, will it keep inserting 100000 records?

I knew I can try it, but I have my notebook was crash today, I have to reinstall everything :(

private async Task Test()
{ 
    AddLoopAsync("xyz", 100000);
}


Private async Task AddLoopAsync(string id, int loop) { 
{
	for (int i = 0; i < loop; i++)
	{
		InsertAsync(id+i.ToString());
	}
}

Private async Task InsertAsync(string idLoop) {

   // Insert into blah blah

}

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-02-07T14:18:55.1466667+00:00

    As written the design will run synchronously.

    Reference documentation

    Asynchronous programming with async and await

    If you are looking for a fire and forget pattern then you'll need to add a Task.Run.

    Google

    However, if you are using Entity Framework then the design will throw an exception unless a new DbContext is created for each insert operation.

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-02-07T16:17:01.5566667+00:00

    Assuming the insert routine calls an async method, the for loop will try to queue up 100k threads. This will probably hit the max threads, and stall.

    as now code await the completion of the thread, the application may exit before the threads complete.

    the parallel library was support for what you are Ing to do. It will use a queue of threads, and not overload.

    https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop

    you can run the ForEach in its own fire and forget thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.