I've been trying to find a design for the situation where you have a type that has a dependency and you want to call a method that returns a Task
. The gut reaction is to do GetAwaiter().GetResult()
but I know that goes against the whole purpose of asynchronous tasks. The thought is to spin up the task but let it do its thing until the type needs it.
public class SomeClass {
private readonly Task<Data> _getDataTask;
private readonly IDependency _dep;
private Data _data;
public SomeClass(IDependency dep) {
_dep = dep;
// I'll spin this up but I don't need the result yet
_getDataTask = _dep.GetDataAsync();
}
public async Task DoSomeWork() {
// Now I need the result of the task so I'll await the task
_data = await _getDataTask;
ExecuteWorkOn(_data);
}
}
Maybe this approach would produce a lot of condition statements to await if you don't have the result cached? I'm hoping to get feedback on this approach in the hopes that either another SO question gets linked or we come up with a design we didn't think about before.
UPDATE 1
I made the Task
to be Task<Data>
as mentioned in one of the comments