Here one my example to insert new record in DB using entity framework core, and Parallel.ForEachAsync.
First install
Microsoft.EntityFrameworkCore, then install
Microsoft.EntityFrameworkCore.SqlServer
FileNamesEntity, or how the table in DB looks like:
public class FileNamesTestEntity
{
[Key] public int Id { get; set; }
public string? FileName { get; set; }
}
FileNamesTestDbContext:
public class FileNamesTestDbContext : DbContext
{
public DbSet<FileNamesTestEntity> FileNamesTest { get; set; }
public FileNamesTestDbContext(DbContextOptions<FileNamesTestDbContext> options) : base(options) { }
}
And the code:
using Microsoft.EntityFrameworkCore;
namespace UpdateOrInsertRecordInDbFromParallelForEachAsync
{
public partial class Form1 : Form
{
private CancellationTokenSource CancellationTokenSource { get; } = new();
public Form1()
{
InitializeComponent();
}
private async void btnStartIProgress_Click(object sender, EventArgs e)
{
int recordCount = 0;
IProgress<int> recordCountProgress = new Progress<int>(NumberOfFilesProcessedIProgress);
IProgress<string> fileNameProgress = new Progress<string>(FileProcessedIProgress);
int progressStep = 100;
var options = new DbContextOptionsBuilder<FileNamesTestDbContext>()
.UseSqlServer("Server=myServer;Database=MyDb;User Id=myUser;Password=myPass;Encrypt=True;TrustServerCertificate=True;")
.Options;
await Parallel.ForEachAsync(Directory.EnumerateFiles(textBox1.Text, "*.*", SearchOption.AllDirectories), new ParallelOptions
{
CancellationToken = CancellationTokenSource.Token
}
, async (fileName, ct) =>
{
await using var dbContext = new FileNamesTestDbContext(options);
FileNamesTestEntity fileNamesTestEntity = new FileNamesTestEntity();
fileNamesTestEntity.FileName = fileName;
dbContext.FileNamesTest.Add(fileNamesTestEntity);
await dbContext.SaveChangesAsync(ct);
recordCount = Interlocked.Increment(ref recordCount);
if (recordCount % progressStep == 0)
{
fileNameProgress.Report(fileName);
recordCountProgress.Report(recordCount);
}
});
MessageBox.Show("Done!");
}
private void FileProcessedIProgress(string fileName)
{
lblIProgressUiFileName.Text = fileName;
}
private void NumberOfFilesProcessedIProgress(int recordCount)
{
lblIProgressUiRecordCount.Text = $"Processed files: {recordCount}";
}
private void btnStopIProgress_Click(object sender, EventArgs e)
{
CancellationTokenSource.Cancel();
}
}
}
Example download from
here