- Details
- Written by: Stanko Milosev
- Category: C#
- Hits: 661
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace GetDbDataTypes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
string connectionString = "Server=myServer;Database=myDb;Integrated Security=True";
string query = "SELECT top 1 * FROM [myTable]";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 3600;
using (SqlDataReader reader = command.ExecuteReader())
{
dataGridView1.DataSource = reader.GetSchemaTable();
}
}
}
}
}
}
Example download from here
- Details
- Written by: Stanko Milosev
- Category: C#
- Hits: 1127
_cts = new System.Threading.CancellationTokenSource();
int[] sleepConfiguration = [5, 7, 10, 1, 3];
List<Task> sleepingTasks = new List<Task>();
foreach (int sleepSeconds in sleepConfiguration)
{
Task sleepingTask = Task.Run(() =>
{
DoSomethingLong(sleepSeconds);
}, _cts.Token);
sleepingTasks.Add(sleepingTask);
}
await Task.WhenAll(sleepingTasks);
MessageBox.Show("Done!");
private void DoSomethingLong(int sleepSeconds)
{
Thread.Sleep(sleepSeconds * 1000);
}
- Details
- Written by: Stanko Milosev
- Category: C#
- Hits: 775
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
- Details
- Written by: Stanko Milosev
- Category: C#
- Hits: 1107
Task task1 = Task.Run(() => throw new SystemException("Test exception in Task.Run"));
Task task2 = Task.Run(async () =>
{
await Task.Delay(1000);
WriteToTextBox("Completed");
});
try
{
await Task.WhenAll(task1, task2);
}
catch (Exception ex)
{
WriteToTextBox(ex.Message);
}
This will output:
Completed Test exception in Task.RunSecond, Task.Run.ContinueWith, exception will be swallowed:
Task task1 = Task.Run(() => throw new SystemException("Test exception in Task.Run"))
.ContinueWith(t => WriteToTextBox("ContinueWith exception test"));
Task task2 = Task.Run(async () =>
{
await Task.Delay(1000);
WriteToTextBox("Completed");
});
try
{
await Task.WhenAll(task1, task2);
}
catch (Exception ex)
{
WriteToTextBox(ex.Message);
}
Output:
ContinueWith exception test CompletedParallel.ForEach, exception will be thrown, but not catched outside of Parallel.ForEach, and program will end:
string[] myItems = ["item1", "item2", "item3", "item4", "item5"];
Task task1;
Task task2;
try
{
Parallel.ForEach(myItems, async void (myItem) =>
{
task1 = Task.Run(() => throw new SystemException("Test exception in Task.Run"));
task2 = Task.Run(async () =>
{
await Task.Delay(1000);
WriteToTextBox(myItem);
});
await Task.WhenAll(task1, task2);
});
}
catch (Exception ex)
{
WriteToTextBox(ex.Message);
}
Parallel.ForEachAsync:
string[] myItems = ["item1", "item2", "item3", "item4", "item5"];
Task task1;
Task task2;
using CancellationTokenSource cts = new();
CancellationToken token = cts.Token;
try
{
int i = 0;
await Parallel.ForEachAsync(myItems, new ParallelOptions
{
CancellationToken = token
}
, async (myItem, ct) =>
{
i = Interlocked.Increment(ref i);
task1 = Task.Run(() => throw new SystemException($"Test exception in Task.Run {i}"), ct);
task2 = Task.Run(async () =>
{
await Task.Delay(1000, ct);
WriteToTextBox(myItem);
}, ct);
await Task.WhenAll(task1, task2);
});
}
catch (Exception ex)
{
WriteToTextBox(ex.Message);
}
Only one exception will be thrown in output:
item4 item2 item1 item5 item3 Test exception in Task.Run 5Example download from here