1


I have been looking at this article about using tasks in C#, and I was wandering if someone could clear something up for me?
Doesn't calling wait on a task defeat the purpose of creating the task, because wouldn't it freeze up the main thread anyway because now the main thread has to wait for task to finish.
I'm assuming however that wait won't be called straight away, so now when would you call it or how else would you know when to dispose of the task. Assuming we have a simple case like this:

    void MyFunction()
    {
        Task t = Task.Factory.StartNew(() => { System.Threading.Thread.Sleep(5000); });
    }

if you call t.Wait() straight away the main thread will still wait 5 seconds before being able to do anything else, which kinda defeats the purpose from the users point of view, they wont be able to do anything for 5 seconds. How would you know that after 5 seconds that task has been completed? And you can dispose of t? What is a correct way of handling that?
Sorry if the question is being really naive :( Thanks All :D

Heinrich
  • 2,144
  • 3
  • 23
  • 39

1 Answers1

6

You would probably never call Wait on a single task like this from a UI thread - as you said the whole point is not blocking the UI thread. In fact waiting on any task at all from the UI thread would be a problem.

Waiting for task completion might however be useful to synchronize multiple tasks and return a combined result - e.g. imagine two tasks that execute a hotel query on priceline and expedia concurrently and the thread that spawned both tasks (e.g. a background thread) waiting on the outcome of both and combining the results to order the available hotels on both sites by price.

The final result of the queries can then be dispatched back to the UI thread, typically by executing a callback or raising an event.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Ahhh true :D Thanks :D so does also mean that the C# GC will deal with the task and clean it up. No need to call .Dispose(). – Heinrich Mar 05 '12 at 08:09
  • @Heinrich: If you do not use any event handles in your task, you don't have to worry about calling `Dispose`, also see http://stackoverflow.com/questions/3734280/is-it-considered-acceptable-to-not-call-dispose-on-a-tpl-task-object – BrokenGlass Mar 05 '12 at 19:33