async function not launching asynchronously

I still meet issues calling async functions.
In that code, I execute generateAllIfcs(dataFolder), then I would like to execute already addToExistingContract() or this.importNewContract() depending on contexte.SourceContract.
But this line is not reached until generateAllIfcs(dataFolder) is finished.

private async void Import(object sender, RoutedEventArgs e)
{
    Task<bool> successGenerateIfc = this.generateAllIfcs(dataFolder);
    Task<bool> successAddContractToVsteel = contexte.SourceContract != null ? this.addToExistingContract() : this.importNewContract();
    await Task.WhenAll(successGenerateIfc, successAddContractToVsteel);
}
private async Task<bool> generateAllIfcs(string dataFolder)
{
    try
    {
        var progressIndicator4 = new Progress<int>(contexte.ReportProgress4);
        if (contexte.SourceContract != null)
        {
            int total4 = await contexte.NewModel.ExportNewIfcContract(contexte.SourceContract, progressIndicator4, 0, 100, contexte.SelectedConfigImportIFC, true,dataFolder);
        }
        else
        {
            int total4 = await contexte.NewModel.ExportNewIfcContract(null, progressIndicator4, 0, 100, contexte.SelectedConfigImportIFC, true,dataFolder);
        }
        return true;
    }
    catch
    {
        return false;
    }
    
}
 public async Task<int> ExportNewIfcContract(Contract existingContract, IProgress<int> progress, int startProgress, int endProgress, ConfigImportIFC config,bool generateIfcAssAndRep, string dataFolder)
{
    int retour = await this.exportNewIfcContract(existingContract, progress,startProgress,endProgress,config, generateIfcAssAndRep,dataFolder);
    return retour;
}
private async Task<int> exportNewIfcContract(Contract existingContract, IProgress<int> progress,int startProgress,int endProgress,ConfigImportIFC config, bool generateIfcAssAndRep,string dataFolder)
{
    //some other calls to async functions
}

>Solution :

"async function not launching asynchronously" – yes, that’s normal; async isn’t about how things launch, it is about how they complete (or at least, continue); async doesn’t mean "parallel", "concurrent", etc – and has only tangential relationship to threading; an async method runs synchronously until the first incomplete await, i.e. where the thing being awaited did not itself finish synchronously. Only for an incomplete await does the async engine unroll itself and register a continuation. I don’t see anything inherently truly async in your code, although to be fair: I can’t see exportNewIfcContract.

If you want concurrency, consider Task.Run etc to invoke a second execution flow. Or alternatively, consider adding:

await Task.Yield();

at the top of generateAllIfcs (the method that you intend to run concurrently); Task.Yield() always returns in an incomplete state, pushing the rest of the work as a continuation onto the thread-pool.

Leave a Reply