Multi-Threading a Large C# Application Using async/await Multi-Threading a Large C# Application Using async/await multithreading multithreading

Multi-Threading a Large C# Application Using async/await


If you're constantly going back and forth between UI and thread pool threads, your code is going to be a bit messy.

You essentially have two options: have your "normal" context be the thread pool thread with portions scheduled to the UI thread (as you have it now), or have your "normal" context be the UI thread with portions scheduled to a thread pool thread.

I usually prefer the latter, since you can use the simpler Task.Run instead of Task.Factory.StartNew on a specific TaskScheduler. But either way, the code is going to be a bit messy.


I didn't work with SpreadsheetGear workbook, but I suppose that it has an event mechanism which you could use for storing relevant data for you in a custom object which you can access from the outside of the UISynchronizationContext, in this way you avoid to be strongly bounded to the workbook UI control. This will permit you to avoid blocking UI thread with

 Task task = Task.Factory.StartNew(() =>{    worksheet = workbookView.ActiveWorksheet;    range = worksheet.UsedRange;}, CancellationToken.None,   TaskCreationOptions.None,   scheduler);try{    task.Wait();}finally{    task.Dispose();}

part from the GenerateStage method.

But again, my suggestion is based on some assumptions about SpreadsheetGear workbook controls, that can be incorrect.