我只是做一些測試同步與異步,並寫下面的程序來測試。 也許我做錯了或者我只是不知道/明白異步正確,爲什麼我的程序的異步版本比同步版本慢?
我看到我的同步版本需要318 ms
而異步需要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();
}
}
另外http://stackoverflow.com/questions/27189082/async-await-makes-my-tasks-slow-while-task-start-runs-them-fast – trailmax
和http://stackoverflow.com/a/15666011/809357 – trailmax
很好的解釋爲什麼使用異步http://stackoverflow.com/a/15665968/809357 – trailmax