-1

Quick question about async-await.

If I have a chunk of code like

object foo; 
Task t1 = LongRunningTaskThatSetsFoo(out foo); 
UseFooToDoSomething(foo);
await t1; 

then what will happen? Because there isn't any independent work to be done between the time when LongRunningTaskThatSetsFoo is allowed to start (line 2) and the time when we wait for its result (line 4).

user7127000
  • 3,143
  • 6
  • 24
  • 41
  • Possible duplicate of [What's the new C# await feature do?](http://stackoverflow.com/questions/4057359/whats-the-new-c-sharp-await-feature-do) – Clint Dec 09 '16 at 15:22
  • Marked as potential duplicate as question title and "then what will happen?" are possibly at odds and the question is more about the internals. async / await always usually has a benefit as it allows the thread to return to the pool and process other things that are going on. – Clint Dec 09 '16 at 15:23
  • 2
    You can't have an `async` method with an `out` parameter. If `LongRunningTaskThatSetsFoo` is not `async`, it will have set `Foo` when it returns. – Dennis_E Dec 09 '16 at 15:28
  • 1
    @Dennis_E Technically it could be a non-async method that just returns a `Task`, but even so, it's probably just wrong. – Servy Dec 09 '16 at 15:32

1 Answers1

0

What will happen? LongRunningTaskThatSetsFoo isn't allowed to return the Task until it has set foo, meaning it has to provide foo when starting the asynchronous operation, and not when the asynchronous operation ends. This probably just doesn't make sense. I suppose technically you could include information about what LongRunningTaskThatSetsFoo is going to do, rather than what it has done, but I'm...skeptical.

Anyway, since foo has to have been set before the asyncrhonous operation would be allowed to start (which is when LongRunningTaskThatSetsFoo returns) UseFooToDoSomething will then use foo, then the method will return and execution will continue after the Task returned by LongRunningTaskThatSetsFoo completes.

You almost certainly don't want to do this. If LongRunningTaskThatSetsFoo produces a value, then it should return a Task<T> where foo is the result of that Task<T>. Of course, asynchronous operations that produce a result aren't in any way useless. They're quite useful. The current thread wouldn't be able to do any work that depended on the result, but they'd be able to perform operations that didn't depend on the result, and let the operations that did depend on the result start running as soon as the result is computed.

Servy
  • 202,030
  • 26
  • 332
  • 449