I have a WPF application in which i have to do a long running task (basically reading from network). Just to give you a snapshot I am doing the following thing on button click
Dim t As Task(Of String) = Task.Factory.StartNew(Of String)(Function()
'Thread.sleep is simulating long running task that will make UI unresponsive
Thread.Sleep(10000)
Return "Hello world from async task"
End Function)
TextBlock1.Text = t.Result
I cannot use Event based async methodology because the reading API actually exist in a dll which i refer in my program, that contains a function Public function ReadFromNetwork() as String. This API is making an async call to network to read a long string and return to UI. So, in short i m doing TextBlock1.Text = ExternalDll.ReadFromNetwork().
but the problem is that even if i use Task asynchrony, the UI is still unresponsive.
Can you please detect if i m missing something in code.
Any help/suggestion will be highly appreciated
Thanx in advance
You’re using
t.Resulton the line after you start the task. That will make the thread block until the task completes – so all the asynchrony is in vain.You should attach a continuation using
Task.ContinueWith, and put the code using the task result into that continuation. That will allow the UI to go back to handling events while the task is executing, and then your continuation will be fired when the task has completed. Pass inTaskScheduler.FromCurrentSynchronizationContextto make sure that the continuation fires on the right thread.Note that in the next version of VB/C#, all this will be much easier with async methods. If you’re able to use the .NET 4.5 release candidate, you should consider trying this right now – it’ll make your life much simpler.