1

As title. Say I have a function:

async Task Foo()
{
    // get Task obj that will be returned from this function
}

Is it possible to get a reference to that Task object?

The reason I'm curious about this, is because I want to be able to keep track of some tasks.

void_Foo
  • 337
  • 1
  • 5
  • 12
  • Could you move that logic into a new `InnerFoo`? And then use the `InnerFoo` `Task` from `Foo`? – mjwills Aug 06 '19 at 12:12
  • 2
    What do you mean by _I want to be able to keep track of some tasks_? If the Task inside of `Foo` is awaited then the task returned by `Foo` will not complete until that one does. – juharr Aug 06 '19 at 12:14
  • Did you have a look at this: https://stackoverflow.com/questions/6700809/how-to-get-the-current-task-reference ? – vsarunov Aug 06 '19 at 12:14
  • 1
    You can't *literally* do this, because the compiler-generated code will not actually produce the task until the end -- so, in a very real sense, there *is* no `Task` object inside the method. There are probably many alternative ways of achieving what you want, but that involves taking a step back and detailing your actual scenario. – Jeroen Mostert Aug 06 '19 at 12:18
  • you are actually asking whether one can access the return value of a method inside the method. – Mong Zhu Aug 06 '19 at 12:18
  • The link posted by @vsarunov comes closest to what I wanted, but seeing the complexity has made me reconsider this. – void_Foo Aug 06 '19 at 13:27
  • 1
    @juharr: I did not want to await the Task inside the function, just add it to a list inside the same class that owns the function, but is not the caller of the function. But I'm going to go a different route now :-). Thanks for the comments! – void_Foo Aug 06 '19 at 13:27

1 Answers1

2

The Task that is returned from the function is the one generated from await Boo() (if the inner work is done by a function Boo) So you can use:

Task booTask = Boo();

without await to get that task.

Efraim Newman
  • 927
  • 6
  • 21
  • 1
    That is unfortunately not true for some corner cases, like ValueTask and Custom Awaiters – user1781290 Aug 06 '19 at 12:16
  • @user1781290 : generally, an async method return a task that is created somewhere, so you can save that created task instead of using `await` – Efraim Newman Aug 06 '19 at 12:19
  • async methods are usually not returning a Task explicitly, but implicitly. Still my point stands, that there are cases where you `await` an object that is not `Task` – user1781290 Aug 06 '19 at 12:21