Why the code below results in:
public static class Program
{
public static void Main(params string[] args)
{
var sourceFileName = @"C:\Users\ehoua\Desktop\Stuff\800MFile.exe";
var destinationFileName = sourceFileName + ".bak";
FileCopyAsync(sourceFileName, destinationFileName);
// The line below is actually faster and a lot less CPU-consuming
// File.Copy(sourceFileName, destinationFileName, true);
Console.ReadKey();
}
public static async void FileCopyAsync(string sourceFileName, string destinationFileName, int bufferSize = 0x1000, CancellationToken cancellationToken = default(CancellationToken))
{
using (var sourceFile = File.OpenRead(sourceFileName))
{
using (var destinationFile = File.OpenWrite(destinationFileName))
{
Console.WriteLine($"Copying {sourceFileName} to {destinationFileName}...");
await sourceFile.CopyToAsync(destinationFile, bufferSize, cancellationToken);
Console.WriteLine("Done");
}
}
}
}
While File.Copy(): https://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.110).aspx is a lot less cpu-consuming:
So is there still a real interest using async / await for file copy purposes?
I thought saving a thread for copying might worth it but the File.Copy windows function seems to win the battle hands down in terms of CPU %. Some would argue it's because of the real DMA support but still, am I doing anything to ruin the performances? Or is there anything that can be done to improve the CPU usage with my async method?
File.Copy
is implemented vs. your direct stream-based approach of usingFile.OpenRead
andFile.OpenWrite
. I doubt it has anything to do with sync vs. async. – LucaniaFile.Copy
which wrappers native Win32 operations for a more low-level approach. See #1247399 – LucaniaStringBuilder
s. In this particular case the only (hypothetical) benefit of using theAsync
version and paying the performance cost, is that it prevents a thread from being blocked. A thread costs 1 MB RAM, so obviously sacrificing 50% of the user's CPU to save 0.01% of their RAM is a bad tradeoff. To add insult to injury, this benefit is not even real: the "async" version still blocks a thread. – Vichyssoise