In my project's code base, I see a lot of methods that boil down to the following code:
public async Task<bool> MyAsyncFunction(string filePath)
{
byte[] fileBytes = await File.ReadAllBytesAsync(filePath);
bool succeeded = await UploadFileSomewhereAsync(fileBytes);
return succeeded;
}
I understand that async/await is useful for non-blocking UI tasks in front-end code. I also understand that async/await can be used to run certain tasks in parallel, as in the code below:
public async Task<bool> MyAsyncFunction(string filePath)
{
Task<byte[]> fileBytesTask = File.ReadAllBytesAsync(filePath);
// do some other work that does not need the file byte array
byte[] fileBytes = await fileBytesTask;
bool succeeded = await UploadFileSomewhereAsync(fileBytes);
return succeeded;
}
However, how is the async/await pattern of any use in the first example? Is there any benefit of writing code like this over simply calling the synchronous versions of these methods? Am I missing something?
Aucun commentaire:
Enregistrer un commentaire