I have something like this:
void GenerateReports() {
foreach (var employee in employees) {
GenerateReport(employee);
}
}
GenerateReport takes long time, and I don’t want to block my UI thread, so I run this method in a separate thread.
However, GenerateReport occasionaly throws an exception. I want to handle each exception in my UI thread, and continue with the next employee. How do I do this while generating reports asynchronously? If I put GenerateReport in another thread, the foreach loop will be very fast and all reports are created at the same time:
void GenerateReports() {
foreach (var employee in employees) {
GenerateReportAsync(employee, OnDoneCallback); // returns immediately
}
}
I still want to create one report at a time, but in a seperate thread, and handling an exception for each employee. How can I best implement this?
if you are using a BackGround Worker for threading you can use its BackgroundWorker.ReportProgress Method details here. To send Data Back to your UI thread.