Home > Back-end >  Running two taks parallely in C#
Running two taks parallely in C#

Time:01-28

I need to compute hashes of two big files (around 10GB) to check for equality. Currently i'm computing one hash at a time, but to save a lot of time i had the idea to parallely compute both hashes at the same time. Heres my method:

private bool checkEquality(FileInfo firstFile, FileInfo secondFile)
{
    //These 2 lines are for creating one hash at a time, currently commented out for 
    //testing purpose
    //byte[] firstHash = createHash(firstFile);
    //byte[] secondHash = createHash(secondFile);

    //My take in running the computing processes parallely
    Task<byte[]> fh = Task.Run(() => createHash(firstFile));
    Task<byte[]> sh = Task.Run(() => createHash(secondFile));

    byte[] firstHash = fh.Result;
    byte[] secondHash = sh.Result;

    for (int i = 0; i < firstHash.Length; i  )
    {
        if (firstHash[i] != secondHash[i]) return false;
    }           
    return true;        
}

Since this is my first time trying to do something like that, i'm not quite sure if the code i wrote does work as i imagine, because i've seen usual use of async methods in combination with the await keyword in other threads, but i cant wrap my head about this concept yet.

Edit: Ok i changed my method to:

private async Task<bool> checkEquality(FileInfo firstFile, FileInfo secondFile)
{
    //These 2 lines are for creating one hash at a time, currently commented out for 
    //testing purpose
    //byte[] firstHash = createHash(firstFile);
    //byte[] secondHash = createHash(secondFile);

    //My take in running the computing processes parallely
    Task<byte[]> fh = Task.Run(() => createHash(firstFile));
    Task<byte[]> sh = Task.Run(() => createHash(secondFile));

    byte[] firstHash = await fh;
    byte[] secondHash = await sh;

    for (int i = 0; i < firstHash.Length; i  )
    {
        if (firstHash[i] != secondHash[i]) return false;
    }           
    return true;        
}

Is this the working way to run both computing processes asynchronously at the same time?

CodePudding user response:

await fh and its next line await sh effectively put your async tasks back into series.

Instead await them both together

var result = await Task.WhenAll(new[]{fh, sh});
byte[] firstHash = result[0];
byte[] secondHash = result[1];
  • Related