My question is regarding a rather inelegant solution to a problem that I came up with a while ago.
I was making a Winform Application to access active directory among other things and needed to thread my application to stop my UI from freezing.
Although I have little knowledge of actual threading (I kept hitting cross-thread access issues), I've built a little function that allowed me to pass an object, act on it in a separate thread and then once it returned to the UI CurrentContext I could act on it again to update the view.
TL;DR
The below function sends a Generic Item to a separate thread, then once acted upon, returns the item and acts on it again.
public static void doThreadedQuery<T>(Func<T> processQuery, Action<T> onComplete)
{
TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task<T> doQuery = new Task<T>(processQuery);
doQuery.ContinueWith((results) => { if (onComplete != null) onComplete(results.Result); }, scheduler);
doQuery.Start();
}
An example usage for something similar is pass an activeDirectory
SearchResultCollection
, parse through it and generate a TreeView/Grid. Then return the populated grid and UI updated without freezing.
Now I have done variants with a progress function/cancellation token etc, but I suppose my question is: on a base level, is there some horrible inefficiency or simple equivalent I am unaware of (aside from the Background Worker I am not overly fond of)?
I feel like I'm re-inventing the wheel here.