0

I'm wondering is this the best way to run two tasks in parallel but without using async/await.

public string Export()
{
    var ifcFilePaths = ExportIfcFiles().ToList();
    Task<List<IfcToCsvGraphExportResult>> graphConverterResults = ConvertIfcToGraphData(ifcFilePaths);
    Task<List<IfcToGltfConversionResult>> gltfConverterResults = ConvertIfcToGltfData(ifcFilePaths);
    List<string> folders = _outputFolderPacker.Pack(graphConverterResults.Result, gltfConverterResults.Result).ToList();

    return _zipPacker.Pack(folders);
}

private Task<List<IfcToCsvGraphExportResult>> ConvertIfcToGraphData(List<string> ifcFilePaths)
    => Task.Run(() => _ifcToCsvGraphExporter.Export(ifcFilePaths).ToList());

private Task<List<IfcToGltfConversionResult>> ConvertIfcToGltfData(List<string> ifcFilePaths)
    => Task.Run(() => _ifcToGltfConverter.Convert(ifcFilePaths).ToList());

I want ConvertIfcToGraphData and ConvertIfcToGltfData methods to run in parallel, but on the other hand I want _outputFolderPacker.Pack() method to wait for both results before processing. My issue is I cannot make main Export() method async/await due to some API limitations.

trashr0x
  • 6,457
  • 2
  • 29
  • 39
Rade Tomovic
  • 298
  • 2
  • 14
  • 3
    I think you could use `Task.WaitAll()` after running tha tasks and before returning from Export function... – Marco May 11 '21 at 21:30

1 Answers1

3

I think you could use Task.WaitAll() after running the tasks and before returning from Export function.

public string Export()
{
    var ifcFilePaths = ExportIfcFiles().ToList();
    Task<List<IfcToCsvGraphExportResult>> graphConverterResults = ConvertIfcToGraphData(ifcFilePaths);
    Task<List<IfcToGltfConversionResult>> gltfConverterResults = ConvertIfcToGltfData(ifcFilePaths);
    
    // This is the missing part
    Task.WaitAll(new[] {graphConverterResults, gltfConverterResults});
    
    List<string> folders = _outputFolderPacker.Pack(graphConverterResults.Result, gltfConverterResults.Result).ToList();

    return _zipPacker.Pack(folders);
}

Some detail can be found on Microsoft docs page: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=net-5.0

Marco
  • 56,740
  • 14
  • 129
  • 152
  • Probably worth mentioning that both existing and proposed solution will in fact satisfy *"but on the other hand I want _outputFolderPacker.Pack() method to wait for both results before processing."* – trashr0x May 11 '21 at 21:40