locked
await and Task.Run

    Question

  • hello

    I am trying to understand await/async

    But a sample found in a blog confused me

    var t1 = await Task.Run(() => { return LongProcess(); });
    
    
    var t2 = Task.Run(() => { return LongProcess(); });
    
    I don't understand the use of await in the first sample that seems to work exactely as the last one

    Thank you!

    Friday, November 2, 2012 9:47 AM

Answers

  • Assuming the return type of LongProcess() is LongProcessResult, then the type of t1 is going to be LongProcessResult, while the type of t2 will be Task<LongProcessResult>.

    If you're familiar with the Task type, then using await is similar to accessing Result, in that it waits for the Task to complete and then it returns its result. The difference is that await works asynchronously, so a thread isn't blocked by doing the waiting.

    Sunday, November 4, 2012 12:24 AM

All replies

  • I believe t1 will wait for the task to run before going to the next line of code.

    T2 will not wait until the task finishes to run before going to the next line of code


    • Edited by Ken Tucker Saturday, November 3, 2012 1:32 PM
    Saturday, November 3, 2012 1:32 PM
  • Assuming the return type of LongProcess() is LongProcessResult, then the type of t1 is going to be LongProcessResult, while the type of t2 will be Task<LongProcessResult>.

    If you're familiar with the Task type, then using await is similar to accessing Result, in that it waits for the Task to complete and then it returns its result. The difference is that await works asynchronously, so a thread isn't blocked by doing the waiting.

    Sunday, November 4, 2012 12:24 AM