简体   繁体   中英

How to use Async Await Inside Loop (having a call to a void method) in c#

private async Task EncryptAllExistingTrackerUsersPasswordsAsync()
{
    var trackerUsers = await _userContext.GetAllTrackerUsers();
    foreach (var user in trackerUsers)
    {
        HashSalt hashsalt = _hash.EncryptPassword(user.Password);
    _userContext.PutEncryptedPasswordBackToDatabase(user.Id, hashsalt.Hash, hashsalt.Salt);
    }
}
public void PutEncryptedPasswordBackToDatabase(int id, string hash, byte[] salt)
{
    var sql = "UPDATE Tracker_Users SET [HashedPassword] = @HashedPassword, [Salt] = @Salt WHERE ID = @TrackerUserId";

_dbManager.ExecuteNonQueryAsync(
sql,
id.AsParam("TrackerUserId"),
hash.AsParam("HashedPassword"),
salt.AsParam("Salt", System.Data.SqlDbType.VarBinary)   );
}

I have this method EncryptAllExistingTrackerUsersPasswordsAsync . What I am trying to achieve is, I want to encrypt all the existing Raw Passwords stored in the Database in one go. What this above method is doing is, fetching all the users from the data, then iterating them one by one and calculating their hashes and then saving those hashes inside the DB again using PutEncryptedPasswordBackToDatabase method. Now what I want is, I want to keep calling this PutEncryptedPasswordBackToDatabase method inside the for loop without waiting for the execution of the previous method call. I want to make it asynchronous. How can I achieve this?

You cannot run multiple queries to the same database simultaneously. All what you can do is releasing UI (your queries won't block it). But you have already achieved that, as your method EncryptAllExistingTrackerUsersPasswordsAsync() is asynchronous.

UPDATE : you can run simultaneous queries, but only if your DBMS on the server is multi-threaded (one query in one thread). But you want to update all rows in a table , and it's definitely not good practice to create thousands of threads, one for each row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM