Home > Back-end >  Will Task.Run improve the performance while making multiple DB Calls
Will Task.Run improve the performance while making multiple DB Calls

Time:03-23

I have a code where I have nearly 20 DB calls in sequence. This was done long time back. All teh DB calls are independent of each other. To improve the performance, I am trying to call the DB calls inside Task.Run(...) and I add this task object inside the list collection. finally I wait for all the task to be completed using Task.WaitAll(tskColl.ToArray());.

Sample snippet.

tskColl.Add(Task.Run(()=> {...}));
tskColl.Add(Task.Run(()=> {...}));
tskColl.Add(Task.Run(()=> {...}));
.....
Task.WaitAll(tskColl.ToArray());
 

I used stopwatcher to see the performance improvement, but I could see there is no improvement in the performance. While executing in sequence it was taking on an average 3.5 seconds and now with Task it is taking around 3.3 seconds.

For nearly 20 DB calls, is that the improvement I wll get.. the machine I use is a 4 core processor machine.. Is there a way I can get under 1.5 seconds.

CodePudding user response:

Is there a way I can get under 1.5 seconds?

Assuming that you've done everything you can to optimize the schema of the database and the associated queries (that all the required indexes are there, and that you don't fetch from the database columns that you don't need), the only way to improve the performance is to increase the RAM of the machine, or upgrade the hardware storage device. There is your bottleneck, not in the number of CPU cores. The database just can't read data any faster from your current storage device, or can't store enough data in memory to avoid reading them again from the storage device on subsequent queries.

CodePudding user response:

Task.Run can improve "responsiveness" if calls that would otherwise have latency, are made in parallel like you did.

Example,

async Task LongRunning(){
 await Task.Delay(5000);
}

and then if you call them like should take 5seconds

tskColl.Add(Task.Run(LongRunning));
tskColl.Add(Task.Run(LongRunning));
tskColl.Add(Task.Run(LongRunning));

Task.WaitAll(tskColl.ToArray());

vs calling await LongRunning() 3 times, which would take 15 seconds

  • Related