Consider an asynchronous operation like obtaining search results from a data storage. Now I want it to be possible, to cancel a currently pending search operation, to start a new one, that in fact replaces the active search, mostly because the search parameters changed meanwhile.
My search is started via TPL (.NET 4.0) new Task and eventually has Continues and of course has callbacks, that invoke UI-Methods on UI-Context.
So, if the search button is pressed again, while search tast is running, I firstly have to stop current task and wait for it to end. If I do that from UI thread, I may run into a deadlock, since Wait() on UI thread blocks it, so a possible Invoke() will never execute.
Therefore, in my current solution, I start a separate task, which waits for running tasks to end/abort and then runs the new ones. This feels a bit bulky and cumbersome and I wonder, if there ain’t no more elegant way, since I need this kind of mechanism frequently.
So am I maybe missing a framework mechanism that’s usable for this kind of scenario? Or what would be a more recommended way?
I believe this is what you are looking for. I have commented the code so most of the reasoning is embedded in the code.
Basically, have your continue functions deal with spinning up a prepped Task.