我写了一个简单的基准,也许是错的,并且给我带来了意想不到的结果……这就是为什么我要请你解释一下,甚至更好地纠正我的例子。
using System;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static void Main(string[] args)
{
var startDate = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
InsertEntity(i);
Console.WriteLine($"{i}");
}
var endDate = DateTime.Now;
Console.WriteLine($"Total elapsed time: {(endDate - startDate).TotalMilliseconds}");
}
static void InsertEntity(int i)
{
using (var context = new TestContext())
{
var entity = new Entity
{
Code = $"Code {i}",
Name = $"Name {i}",
Description = $"Description {i}"
};
context.Entities.Add(entity);
context.SaveChanges();
}
}
}
}
总经过时间:9585ms
using System;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static void Main(string[] args)
{
var startDate = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
InsertEntity(i).Wait();
Console.WriteLine($"{i}");
}
var endDate = DateTime.Now;
Console.WriteLine($"Total elapsed time: {(endDate - startDate).TotalMilliseconds}");
}
static async Task InsertEntity(int i)
{
using (var context = new TestContext())
{
var entity = new Entity
{
Code = $"Code {i}",
Name = $"Name {i}",
Description = $"Description {i}"
};
await context.Entities.AddAsync(entity);
await context.SaveChangesAsync();
}
}
}
}
总经过时间:13479ms
我希望反过来,因为异步编程可以在I / O绑定操作期间释放线程...这是正确的吗?那么为什么它实际上要慢一些?