如何使用C#并行编程向字段中插入数据
How to insert data into a field using C # parallel programming
我正在使用 Entity Framework 和 Linq 技术,但是当我尝试使用 parallel.For 时,出现异常
这是我的尝试
class Program
{
static void Main(string[] args)
{
DbContextClass db = new DbContextClass();
Parallel.For(0, 10, i =>
{
Category ct = new Category
{
NameCategory = "SomeText"
};
db.Categories.Add(ct);
});
db.SaveChanges();
Console.ReadKey();
}
}
检查一下 github issue here
Work on the assumption that none of the code is thread safe. All of the main APIs, like DbContext, DbSet, etc. are not thread safe. There are some thread safe parts, which are usually singleton or similar shared services, but almost all of that is internal.
这并不意味着您不能与同一个 DBContext
并行工作。只需将您的代码更改为以下内容(每次都创建一个新的 DBContext):
class Program
{
static void Main(string[] args)
{
Parallel.For(0, 10, i =>
{
using(DbContextClass db = new DbContextClass()) {
Category ct = new Category
{
NameCategory = "SomeText"
};
db.Categories.Add(ct);
db.SaveChanges();
}
});
Console.ReadKey();
}
}
我正在使用 Entity Framework 和 Linq 技术,但是当我尝试使用 parallel.For 时,出现异常
这是我的尝试
class Program
{
static void Main(string[] args)
{
DbContextClass db = new DbContextClass();
Parallel.For(0, 10, i =>
{
Category ct = new Category
{
NameCategory = "SomeText"
};
db.Categories.Add(ct);
});
db.SaveChanges();
Console.ReadKey();
}
}
检查一下 github issue here
Work on the assumption that none of the code is thread safe. All of the main APIs, like DbContext, DbSet, etc. are not thread safe. There are some thread safe parts, which are usually singleton or similar shared services, but almost all of that is internal.
这并不意味着您不能与同一个 DBContext
并行工作。只需将您的代码更改为以下内容(每次都创建一个新的 DBContext):
class Program
{
static void Main(string[] args)
{
Parallel.For(0, 10, i =>
{
using(DbContextClass db = new DbContextClass()) {
Category ct = new Category
{
NameCategory = "SomeText"
};
db.Categories.Add(ct);
db.SaveChanges();
}
});
Console.ReadKey();
}
}