I was just doing some tests on sync vs async and wrote following program to test. Maybe I have done something wrong or I just don't get/understand async correctly,
I see my sync version takes 318 ms
while async takes 18764 ms
static void Main(string[] args)
{
int num = 25;
Task[] tasks = new Task[num];
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < num; i++)
{
int c = i;
tasks[i] = Task.Factory.StartNew(() => { RunAsync(c).Wait(); });
}
Task.WaitAll(tasks);
sw.Stop();
Console.WriteLine($"FINISHED (Async) in {sw.ElapsedMilliseconds} ms");
sw.Start();
for (int i = 0; i < num; i++)
{
RunSync(i + 100);
}
sw.Stop();
Console.WriteLine($"FINISHED (Sync) in {sw.ElapsedMilliseconds} ms");
Console.ReadLine();
}
private static void RunSync(int index)
{
FileStream stream = new FileStream(@"c:\\test\ff\tests.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
string pp = Path.Combine(@"c:\\test\ff", "threadS-" + index + ".txt");
FileStream sw = File.Create(pp);
byte[] buffer = new byte[1024];
long bytesRead = 0;
long bytestoRead = stream.Length;
try
{
while (bytesRead < bytestoRead)
{
int count = stream.Read(buffer, 0, buffer.Length);
bytesRead += count;
sw.Write(buffer, 0, count);
}
}
finally
{
sw.Close();
stream.Close();
}
}
private async static Task RunAsync(int index)
{
FileStream stream = new FileStream(@"c:\\test\ff\tests.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
int tId = Thread.CurrentThread.ManagedThreadId;
string pp = Path.Combine(@"c:\\test\ff", "thread-" + index + ".txt");
FileStream sw = File.Create(pp);
byte[] buffer = new byte[1024];
long bytesRead = 0;
long bytestoRead = stream.Length;
try
{
while (bytesRead < bytestoRead)
{
int count = await stream.ReadAsync(buffer, 0, buffer.Length);
bytesRead += count;
await sw.WriteAsync(buffer, 0, count);
}
}
finally
{
sw.Close();
stream.Close();
}
}