Serj Sagan Serj Sagan - 3 months ago 8
C# Question

Where is the OnCompleted callback for Task?

I'd like to be be able to do this:

class MyClass
{
IRepo repo;
public MyClass(IMyRepo repo) { this.repo = repo; }

long ID { get; set; }
string Prop1 { get; set; }
string Prop2 { get; set; }

public async Task LoadAsync()
{
await Task.WhenAll(
repo.GetProp1ByIDAsync(ID).OnComplete(x => Prop1 = x),
repo.GetProp2ByIDAsync(ID).OnComplete(x => Prop2 = x)
);
}
}


Of course, I can't seem to find any standard library that has this
OnComplete
extension for
Task
. Do I really need to create my own or is there a library that already has this extension method? I see that there's
ContinueWith
but that does not give me the unwrapped result, I still have to
await
it or
.Result
it... so wouldn't that block the thread? Holding up the second
repo
call until this completed? If it doesn't hold it up then why am I getting that result still wrapped, would it be cleaner to return the unwrapped result to me? Or am I missing something?

Answer

First you should got for await Task.WhenAll(...) instead of .WaitAll.

ContinueWith is what you need to fire up another task on completion. Calling .Result on the unwrapped result passed to the ContinueWith would return instantly as the the task has already completed, same goes if you await it.

Calling .ContinueWith on the first task has no effect on the second one, and as you are awaiting them later using await Task.WhenAll(...) they would execute in paralell.

checkout this link with the ReadFileAsync example.

Comments