System.InvalidOperationException:'集合已被修改;枚举操作可能无法执行。 [英] System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
本文介绍了System.InvalidOperationException:'集合已被修改;枚举操作可能无法执行。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个应用程序,用于将数据存储到数据库中的API。
我低于此错误。
" System.InvalidOperationException:'集合已被修改;枚举操作可能无法执行。'"
我的代码是
public static void GetAllInfluencers()
{
sw.Start();
列表< InfluencerHelperModel> influencerHelperModelList = new List< InfluencerHelperModel>();
使用(TuesdayAppEntities dataContext = new TuesdayAppEntities())
{
schdulerJob =(from c in dataContext.SchdulerJobs.AsEnumerable()select c).FirstOrDefault();
do
{
List< ImportedInfluencer> partilaInfluencers =(from datacer in dataContext.ImportedInfluencers.AsEnumerable()select influencer).Skip(offset).Take(limit).ToList();
列表<任务> allTasks = new List< Task>();
Console.WriteLine(" cycle begin");
foreach(partilaInfluencers中的ImportedInfluencer影响者)
{
InfluencerHelperModel influencerHelperModel = new InfluencerHelperModel();
influencerHelperModel.influencer = influencer;
influencerHelperModel.serachListResponses = new List< Google.Apis.YouTube.v3.Data.SearchResult>();
influencerHelperModel.youtubeSubscriberCount = string.Empty;
influencerHelperModel.channelListResponse = new Google.Apis.YouTube.v3.Data.ChannelListResponse();
influencerHelperModel.statusList = new List< LinqToTwitter.Status>();
influencerHelperModel.user = new LinqToTwitter.User();
influencerHelperModel.tumblrPosts = new List< Post>();
allTasks.Add(Task.Factory.StartNew(()=> {new YoutubeHelper()。GetData(influencerHelperModel,schdulerJob);})。ContinueWith(t => UpdateAll (influencerHelperModelList.ToList())));
allTasks.Add(Task.Factory.StartNew(()=> {new TwitterHelper()。GetData(influencerHelperModel,schdulerJob);})。ContinueWith(t2 => UpdateAll(influencerHelperModelList.ToList())) );
allTasks.Add(Task.Factory.StartNew(()=> {new TumblrHelper()。GetData(influencerHelperModel,schdulerJob); UpdateAll(influencerHelperModelList);})。ContinueWith(t3 => UpdateAll(influencerHelperModelList。 ToList())));
influencerHelperModelList.Add(influencerHelperModel);
}
Task.WaitAll(allTasks.ToArray());
Console.WriteLine(" cycle finished");
offset = offset + limit;
if(offset> dataContext.ImportedInfluencers.Count())
{
break;
}
} while(true);
// SchdulerJob schdulerUpdateJob = new SchdulerJob();
// schdulerUpdateJob =(来自c中的dataContext.SchdulerJobs.AsEnumerable()select c).FirstOrDefault();
// if(schdulerUpdateJob == null || schdulerUpdateJob.WeeklyJobLastRun == null || schdulerUpdateJob.WeeklyJobLastRun.Value.AddDays(7)< = DateTime.Now)
// {
// schdulerUpdateJob.WeeklyJobLastRun = DateTime.Now;
// dataContext.SaveChanges();
//}
Console.WriteLine(sw.ElapsedMilliseconds / 1000 +" seconds");
}
}
首先执行任务后,我们将数据写入数据库中lock 线程功能。请参阅代码。
public static void UpdateAll(List< InfluencerHelperModel> influencerHelperModelList)
{
lock(influencerHelperModelList)
{
使用(TuesdayAppEntities dataContext = new TuesdayAppEntities())
{
foreach(InflucerHelperModel influencerModel in influencerHelperModelList)
{
foreach(SearchResult searchResult in influencerModel.serachListResponses)
{
if(!dataContext.YoutubePosts.Any(i => i.VideoId == searchResult.Id.VideoId))
{
YoutubePost youtubePost = new YoutubePost();
youtubePost.VideoId = searchResult.Id.VideoId;
youtubePost.VideoUrl = string.Format(" https://www.youtube.com/watch?v = {0}",searchResult.Id.VideoId);
youtubePost.Title = searchResult.Snippet.Title;
youtubePost.CreatedDate = searchResult.Snippet.PublishedAt;
youtubePost.InfluencersId = influencerModel.influencer.Id;
youtubePost.Description = searchResult.Snippet.Description;
dataContext.YoutubePosts.Add(youtubePost);
dataContext.SaveChanges();
}
}
foreach(influencerModel.statusList中的状态)
{
string statusId = status.StatusID.ToString() ;
if(!dataContext.TwitterPosts.Any(i => i.TweetId == statusId))
{
TwitterPost twitterPost = new TwitterPost();
twitterPost.tweet = status.Text;
twitterPost.TweetId = status.StatusID.ToString();
twitterPost.InfluencerId = influencerModel.influencer.Id;
twitterPost.CreatedDate = status.CreatedAt;
dataContext.TwitterPosts.Add(twitterPost);
dataContext.SaveChanges();
}
}
foreach(InflucerModel.tumblrPosts中的帖子)
{
string Id = post.Id的ToString();
if(!dataContext.TumblrPosts.Any(i => i.postId == Id))
{
TumblrPost tumblrPost = new TumblrPost();
tumblrPost.post = post.Body;
tumblrPost.InfluencerId = influencerModel.influencer.Id;
tumblrPost.postId = post.Id.ToString();
tumblrPost.postUrl = post.PostUrl;
tumblrPost.createdDate = Convert.ToDateTime(post.Date);
dataContext.TumblrPosts.Add(tumblrPost);
dataContext.SaveChanges();
}
}
ImportedInfluencer uInfluencer = new ImportedInfluencer();
uInfluencer =(来自dataContext.ImportedInfluencers.AsEnumerable()中的c,其中c.Id == influencerModel.influencer.Id select c).FirstOrDefault();
uInfluencer.mostReleventNumberOfFollowersYoutube = influencerModel.youtubeSubscriberCount;
uInfluencer.youtubeAvatar =((influencerModel.channelListResponse == null)||(influencerModel.channelListResponse.Items == null)|| influencerModel.channelListResponse.Items.Count == 0)?
influencerModel。 user.ProfileImageUrl:influencerModel.channelListResponse.Items [0] .Snippet.Thumbnails.High.Url);
uInfluencer.channelCreationDate =((influencerModel.channelListResponse == null)||(influencerModel.channelListResponse.Items == null)||(influencerModel.channelListResponse.Items.Count == 0))? null:influencerModel.channelListResponse.Items [0] .Snippet.PublishedAt;
uInfluencer.mostReleventNumberOfFollowersTwitter = influencerModel.user.FollowersCount.ToString();
uInfluencer.twitterAccCreationDate = influencerModel.user.CreatedAt;
dataContext.SaveChanges();
}
}
}
}
我的错误的解决方案是什么,以及增加流程时间的最佳方法是什么。
谢谢
解决方案
它是哪一行?
I am creating one app for storing the data to the API in to the data base.
I am getting below this errror.
"System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'"
My code is
public static void GetAllInfluencers() { sw.Start(); List<InfluencerHelperModel> influencerHelperModelList = new List<InfluencerHelperModel>(); using (TuesdayAppEntities dataContext = new TuesdayAppEntities()) { schdulerJob = (from c in dataContext.SchdulerJobs.AsEnumerable() select c).FirstOrDefault(); do { List<ImportedInfluencer> partilaInfluencers = (from influencer in dataContext.ImportedInfluencers.AsEnumerable() select influencer).Skip(offset).Take(limit).ToList(); List<Task> allTasks = new List<Task>(); Console.WriteLine("cycle begin"); foreach (ImportedInfluencer influencer in partilaInfluencers) { InfluencerHelperModel influencerHelperModel = new InfluencerHelperModel(); influencerHelperModel.influencer = influencer; influencerHelperModel.serachListResponses = new List<Google.Apis.YouTube.v3.Data.SearchResult>(); influencerHelperModel.youtubeSubscriberCount = string.Empty; influencerHelperModel.channelListResponse = new Google.Apis.YouTube.v3.Data.ChannelListResponse(); influencerHelperModel.statusList = new List<LinqToTwitter.Status>(); influencerHelperModel.user = new LinqToTwitter.User(); influencerHelperModel.tumblrPosts = new List<Post>(); allTasks.Add(Task.Factory.StartNew(() => { new YoutubeHelper().GetData(influencerHelperModel, schdulerJob);}).ContinueWith(t=> UpdateAll(influencerHelperModelList.ToList()))); allTasks.Add(Task.Factory.StartNew(() => { new TwitterHelper().GetData(influencerHelperModel, schdulerJob); }).ContinueWith(t2 => UpdateAll(influencerHelperModelList.ToList()))); allTasks.Add(Task.Factory.StartNew(() => { new TumblrHelper().GetData(influencerHelperModel, schdulerJob); UpdateAll(influencerHelperModelList); }).ContinueWith(t3 => UpdateAll(influencerHelperModelList.ToList()))); influencerHelperModelList.Add(influencerHelperModel); } Task.WaitAll(allTasks.ToArray()); Console.WriteLine("cycle finished"); offset = offset + limit; if (offset > dataContext.ImportedInfluencers.Count()) { break; } } while (true); //SchdulerJob schdulerUpdateJob = new SchdulerJob(); //schdulerUpdateJob = (from c in dataContext.SchdulerJobs.AsEnumerable() select c).FirstOrDefault(); //if (schdulerUpdateJob == null || schdulerUpdateJob.WeeklyJobLastRun == null || schdulerUpdateJob.WeeklyJobLastRun.Value.AddDays(7) <= DateTime.Now) //{ // schdulerUpdateJob.WeeklyJobLastRun = DateTime.Now; // dataContext.SaveChanges(); //} Console.WriteLine(sw.ElapsedMilliseconds / 1000 + " seconds"); } }
After execution the task first we are writing the data into the database by the lock thread feature. See the code.
public static void UpdateAll(List<InfluencerHelperModel> influencerHelperModelList) { lock (influencerHelperModelList) { using (TuesdayAppEntities dataContext = new TuesdayAppEntities()) { foreach (InfluencerHelperModel influencerModel in influencerHelperModelList) { foreach (SearchResult searchResult in influencerModel.serachListResponses) { if (!dataContext.YoutubePosts.Any(i => i.VideoId == searchResult.Id.VideoId)) { YoutubePost youtubePost = new YoutubePost(); youtubePost.VideoId = searchResult.Id.VideoId; youtubePost.VideoUrl = string.Format("https://www.youtube.com/watch?v={0}", searchResult.Id.VideoId); youtubePost.Title = searchResult.Snippet.Title; youtubePost.CreatedDate = searchResult.Snippet.PublishedAt; youtubePost.InfluencersId = influencerModel.influencer.Id; youtubePost.Description = searchResult.Snippet.Description; dataContext.YoutubePosts.Add(youtubePost); dataContext.SaveChanges(); } } foreach (Status status in influencerModel.statusList) { string statusId = status.StatusID.ToString(); if (!dataContext.TwitterPosts.Any(i => i.TweetId == statusId)) { TwitterPost twitterPost = new TwitterPost(); twitterPost.tweet = status.Text; twitterPost.TweetId = status.StatusID.ToString(); twitterPost.InfluencerId = influencerModel.influencer.Id; twitterPost.CreatedDate = status.CreatedAt; dataContext.TwitterPosts.Add(twitterPost); dataContext.SaveChanges(); } } foreach (Post post in influencerModel.tumblrPosts) { string Id = post.Id.ToString(); if (!dataContext.TumblrPosts.Any(i => i.postId == Id)) { TumblrPost tumblrPost = new TumblrPost(); tumblrPost.post = post.Body; tumblrPost.InfluencerId = influencerModel.influencer.Id; tumblrPost.postId = post.Id.ToString(); tumblrPost.postUrl = post.PostUrl; tumblrPost.createdDate = Convert.ToDateTime(post.Date); dataContext.TumblrPosts.Add(tumblrPost); dataContext.SaveChanges(); } } ImportedInfluencer uInfluencer = new ImportedInfluencer(); uInfluencer = (from c in dataContext.ImportedInfluencers.AsEnumerable() where c.Id == influencerModel.influencer.Id select c).FirstOrDefault(); uInfluencer.mostReleventNumberOfFollowersYoutube = influencerModel.youtubeSubscriberCount; uInfluencer.youtubeAvatar = (((influencerModel.channelListResponse == null) || (influencerModel.channelListResponse.Items == null) || influencerModel.channelListResponse.Items.Count == 0) ? influencerModel.user.ProfileImageUrl : influencerModel.channelListResponse.Items[0].Snippet.Thumbnails.High.Url); uInfluencer.channelCreationDate = ((influencerModel.channelListResponse == null) || (influencerModel.channelListResponse.Items == null) || (influencerModel.channelListResponse.Items.Count == 0)) ? null : influencerModel.channelListResponse.Items[0].Snippet.PublishedAt; uInfluencer.mostReleventNumberOfFollowersTwitter = influencerModel.user.FollowersCount.ToString(); uInfluencer.twitterAccCreationDate = influencerModel.user.CreatedAt; dataContext.SaveChanges(); } } } }
what is the solution of my error and what is the best way to increase the time of process.
thanks
解决方案
Which line is it?
这篇关于System.InvalidOperationException:'集合已被修改;枚举操作可能无法执行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文