Awaitable method call event when finished

I have synchronous method, that calls async method:

private void Sync_Click(object sender, EventArgs e)
{
    CancellationToken token = new CancellationToken();
    SyncAllMappings(token);            
}

async void SyncAllMappings(CancellationToken token)
{
    //create collection of tasks per each mapping
    IEnumerable<Task<Task>> tasks = SomeLogicHere();
    await Task.WhenAll(tasks);
}

The control returns to user before all tasks are done. Is it possible to get notified, when all tasks have finished? I would like to be able to call some other method, that would display text and enable few buttons, when all tasks finish (and all mappings are in sync).

SyncAllMappings method is in different assembly. Business and UI layers are separated. I don't want to call UI methods directly in SyncAllMappings.

Jon Skeet
people
quotationmark

The control returns to user before all tasks are done.

Yes, that's how async works. Instead of having an async void method, you should make it async Task - and then make your Sync_Click method async as well, so you can await the result:

private async void Sync_Click(object sender, EventArgs e)
{
    CancellationToken token = new CancellationToken();
    await SyncAllMappings(token);            
    // Do whatever you want here, e.g. raising an event
}

async Task SyncAllMappings(CancellationToken token)
{
    //create collection of tasks per each mapping
    IEnumerable<Task<Task>> tasks = SomeLogicHere();

    await Task.WhenAll(tasks);
}

people

See more on this question at Stackoverflow