I know this question has been asked here before, but I've read through several answers that haven't helped me.
I have a ComboBox that needs to get some information related to a selection from a database (probably on lost focus, to stop a thousand calls during scrolling). This information is for display only, and not critical, so getting on a background thread/task sounds like the perfect solution. It does take several seconds though, as it is getting counts from some very large tables. The user should be free to move on to other tasks, as this information really is just for display/reference only.
This question advocates using a Background worker, but this solution has two issues. 1) Changing the selection while the worker is already running introduces problems. You can either not start it the second time, meaning when it returns it is no longer showing valid info for the new selection, or try to cancel it (which doesn't always work). 2) For some reason I cannot explain, the method that actually accesses the database for the background worker returns slower if the method is in Model than if in the ViewModel, where I do not think it belongs. I really don't know why.
This question has several votes, but the OP's question is worded very poorly, and the selected answer just says "yeah that should work."
This question's method looks promising, but the linked video is an hour long (I watched the whole thing), and touches on the dispatcher only for 10-15 seconds without explaining it. If someone has a link to an article that covers this method more in-depth, that would be good.
Thread pooling, as suggested here looks like it is probably the best way to go, as multiple requests for lookup just get queued, instead of causing already-running errors. However, it has no explanation of how to use a thread pool, instead linking to the MSDN article. If someone has a link to an article that covers this method more in-depth, that would be ideal, as it seems like the better solution (of course, I could be wrong).
I really tried to do my research on this one, but most of these answers just tell you what method to use, not how to use it. I am really looking for a "how-to."
OK. Your question:
What you should do, with the latest .NET technologies:
I think if you use the Async CTP with Rx, it is about 10 lines of code.
Note: If your operation is NOT EXPENSIVE, you don't have to use a cancellation token. Just allow the task to run to completion, but ignore the result. However, it is still recommended that you cancel a database query early, although it is not expensive on the client machine, it is expensive on the server.
You could try to use an async binding:
<ComboBox Name="theCombo" ... />
<TextBlock Text="{Binding Path=SomeSlowProperty, ElementName=theCombo, IsAsync=True}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With