It's not clear what you're ultimately trying to do here, but if your goal is high performance, this is the absolute wrong way to achieve that. Task.Run
is going to pull a new thread from the pool each time you call it, so with two items in your list, your action is now consuming three threads (one for the request and one for each list item). Obviously, as the list items scale, so does your thread usage, so you're dramatically cutting the potential throughput of your server, and may actually end up being thread-starved.
It's not clear what _ADB.SaveLogView
is doing, but if it does synchronous work, you need to realize that using Task.Run
doesn't make it async. Sync is still sync, you're just blocking a different thread instead of the request thread. However, since you're awaiting task completion, the request thread is still blocked, so you're actually not achieving anything other than just wasting a bunch of threads that could be handling other requests.
If _ADB.SaveLogView
is async (in which case you should name it _ADB.SaveLogViewAsync
to avoid confusion), then you can simplify your code (and avoid wasting threads) by just doing:
var tasks = new Task[lv.Count];
for (int i = 0; i < lv.Count; i++)
{
tasks[i] = _ADB.SaveLogViewAsync(lv[i]);
}
Since it should already be returning a Task
in that scenario, there's no need to wrap it in another Task
.
However, ideally, you should actually being handling this transactionally. If there's a problem saving one of these entities, the others still get saved. That can cause problems then if you need to resubmit to save the entity or entities that failed. Again, it's not clear what this method is doing, but with something like Entity Framework, you would simply add each new entity to the DbSet
(which marks them as to be created in the change tracking) and then call SaveChangesAsync
just once, which would attempt to save all the items in one go, wrapped in a transaction, so if any fail, everything gets rolled back.
If you're using Entity Framework or some other system that supports transactions under the hood, you should be utilizing that functionality. If you're doing some sort of manual database work, then you should roll your own transactions.