void ResultEventHandler(object sender, ResultEventArgs args) { var result = args.Result; int index = 0; lock (ImageResults) { foreach (var image in ImageResults) { if (image.Path == result.Path) { index = ImageResults.IndexOf(image); break; } } Dispatcher.UIThread.InvokeAsync(() => { lock (ImageResults) { ImageResults[index] = new MNISTModelResultDb(result); ImageClasses[result.Class].Add(new MNISTModelResultDb(result)); ClassesInfo[result.Class] = ClassInfoProcess(result.Class, ImageClasses[result.Class].Count); processed++; ProdProgressInfo(); } }); Task.Run(() => { lock (dbContext) { Bitmap resImage = new Bitmap(result.Path); Blob resBlob = new Blob { Bytes = ImageToByteArray(resImage) }; dbContext.ClassifiedImages.Add(new ClassifiedImage { Path = result.Path, Class = result.Class, Confidence = result.Confidence, RetrieveCount = 0, Image = resBlob }); dbContext.Blobs.Add(resBlob); dbContext.SaveChanges(); } }); } }
public async Task PredImages(string dirPath) { var imagePaths = await Task.Run <IEnumerable <string> >(() => { return(Directory.EnumerateFiles(dirPath)); }); ImageResults.Clear(); Source = new CancellationTokenSource(); foreach (var imageClass in ImageClasses) { imageClass.Clear(); ClassesInfo[ImageClasses.IndexOf(imageClass)] = ClassInfoProcess(ImageClasses.IndexOf(imageClass), 0); } ParallelOptions options = new ParallelOptions(); options.CancellationToken = Source.Token; processed = 0; numOfImages = imagePaths.Count(); ProdProgressInfo(); dbContext = new ImageDbContext(); await Task.Run(() => { Parallel.ForEach(imagePaths, options, (imagePath) => { List <string> imagesToClassify = new List <string>(); if (Source.Token.IsCancellationRequested) { return; } MNISTModelResultDb dbImage = null; dbImage = FindImageInDb(imagePath); if (dbImage != null) { Dispatcher.UIThread.InvokeAsync(() => { lock (ImageResults) { ImageResults.Add(dbImage); ImageClasses[dbImage.Class].Add(dbImage); ClassesInfo[dbImage.Class] = ClassInfoProcess(dbImage.Class, ImageClasses[dbImage.Class].Count); processed++; ProdProgressInfo(); } }); } else { Dispatcher.UIThread.InvokeAsync(() => { lock (ImageResults) { ImageResults.Add(new MNISTModelResultDb(imagePath)); } }); imagesToClassify.Add(imagePath); model.PredImages(imagesToClassify, Source.Token).Wait(); } }); }); }