Waiting on asynchronous file loading


I am using the FileChooser class and want to wait on the file dialog in my code. Is there a simple way to do this without using std::futures or something? I tried using the functions that require JUCE_MODAL_LOOPS to be set to on (because those do not operate asynchronously but this causes the UI to randomly hang after the file loading

In a modern approach you don’t wait, but instead you specify what should happen once done.
And you can even use that if the next operation should happen on the message thread if you want.

Something along those lines:

void download (juce::URL url, std::function<void(juce::File)> onFinish)
    juce::File file;
    url.downloadToFile (file);
    onFinish (file);

I’m confused by what you mean here. Perhaps some more info on my use case might clear things up. What I am doing is loading in a preset that contains wave tables. I have 3 oscillators and they are all wav table oscillators, but if you load a preset and it doesn’t know where that wav table file is it will prompt you with the FileChooser dialog. In the case where it doesn’t find any of them it will prompt you with 3 dialogs, but what I’d like it to do is prompt for each oscillator one at a time. It’s a bit convoluted to keep calling FC dialogs within FCdialogs finish function, but waiting on the message thread hangs (as I found out while trying to do just that. )

This could very well be one of those things where it just ain’t gonna happen which isn’t the end of the world I guess. Although I still don’t quite know why the browseForFileToOpen() stuff caused my UI to randomly hang

How can i do this?

Even though it doesn’t seem to fit the OPs purpose any longer, this is how I would e.g. call something on the message thread with a downloaded object:

// this should be called from a background thread
void backgroundDownload (juce::URL url, juce::WeakReference<Foo> receiver)
    auto file = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("data.txt");
    url.downloadToFile (file, options);

    juce::MessageManager::callAsync ([file, receiver]() 
        if (receiver)
            receiver->doSomethingWith (file);
1 Like

This might be one of those cases why modal loops were deactivated by default lately.

If you are already in a modal loop and enter another instance of browseOfFileToOpen weird things may happen. I cannot explain the details, as I simply accept it as a rule to avoid modal loops.