내 질문은 아래 코드에서 인스턴스 메소드가 내가 생각하는 변수에 액세스 할 수 있는지 또는 여전히 작동하는 동안 다른 스레드에 의해 변경 될 수 있는지 확인할 수 있습니까? ? 폐쇄와 관련이 있습니까? 즉, 열거 형은 안전하므로 IEnumerable<T>
의 로컬 복사본에서 작업 할 예정입니까?멀티 스레딩, lambdas 및 로컬 변수
내 질문을 의역으로 말하면, 공유 변수를 작성하지 않으면 잠금이 필요합니까?
public class CustomerClass
{
private Config cfg = (Config)ConfigurationManager.GetSection("Customer");
public void Run()
{
var serviceGroups = this.cfg.ServiceDeskGroups.Select(n => n.Group).ToList();
var groupedData = DataReader.GetSourceData().AsEnumerable().GroupBy(n => n.Field<int>("ID"));
Parallel.ForEach<IGrouping<int, DataRow>, CustomerDataContext>(
groupedData,
() => new CustomerDataContext(),
(g, _, ctx) =>
{
var inter = this.FindOrCreateInteraction(ctx, g.Key);
inter.ID = g.Key;
inter.Title = g.First().Field<string>("Title");
this.CalculateSomeProperty(ref inter, serviceGroups);
return ctx;
},
ctx => ctx.SubmitAllChanges());
}
private Interaction FindOrCreateInteraction(CustomerDataContext ctx, int ID)
{
var inter = ctx.Interactions.Where(n => n.Id = ID).SingleOrDefault();
if (inter == null)
{
inter = new Interaction();
ctx.InsertOnSubmit(inter);
}
return inter;
}
private void CalculateSomeProperty(ref Interaction inter, IEnumerable<string> serviceDeskGroups)
{
// Reads from the List<T> class instance variable. Changes the state of the ref'd object.
if (serviceGroups.Contains(inter.Group))
{
inter.Ours = true;
}
}
}
CustomerDataContext 구현을 공유 할 수 있습니까? 이것은 데이터 경쟁이 현재 발생할 수있는 유일한 장소 인 것처럼 보입니다. –
CustomerDataContext는 표준 Entity Framework DataContext이며 실제로는 스레드 로컬이므로 아무 데이터도 존재하지 않습니다. –