Here’s a quick example on how to implement an asynchronous call in WPF using the System.Threading.Tasks.Task class. Keep in mind that underneath, the call will still end up in a thread pool, as opposed to a ThreadPool approach.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public void StartAsyncTask() { Task<int>.Factory .StartNew(DoAsynkWork) .ContinueWith(ValidateResults, TaskScheduler.FromCurrentSynchronizationContext()); } private int DoAsyncWork() { // Do work and return result. } private void ValidateResults(Task<int> task) { if (task.IsFaulted) { return; } var result = task.Result; // Do some UI Thread stuff... } |
The trick is to use TaskScheduler.FromCurrentSynchronizationContext() to make sure we can work in the UI Thread. ContinueWith sets up a follow-up call to do some final work and that’s it.
Read more





