App crashes if closing a dialog while Async Operations are still underway

Firstly I'm not familiar with using Async, so the below approach could be completely wrong. I'm currently decoding multiple images and displaying them in a dialog window.

This works fine, as long as I don't attempt to close the dialog while the decodes are still running.

If I do close the dialog, I get a Debug Assertion Error at return hh;

In my class header I have:

class CmytestDlg: public CDialog
{

protected:
    // Generated message map functions
    BOOL OnInitDialog() override;
    std::future<HBITMAP> futurebmps[12];

};

In the .cpp:

BOOL CmytestDlg::OnInitDialog()
{
    int totalJobs = 12;

    // Queue up all the items,
    for (int i = 0; i < totalJobs; i++)
    {
        futurebmps[i] = std::async(std::launch::async,
            [this](const int i, const std::string& name) {

        // This line is just here to simulate a long running image decode
        std::this_thread::sleep_for(std::chrono::seconds(10));

        HBITMAP hh = nullptr;
        PostMessage(8888, i, 0); // Send a message to display the image
        return hh; // <<< Debug Assertion Error Here (If I close dialog to soon)
    
        }, i, std::to_string(0));
        
}

The message to draw the image is handled by OnRefreshAsyncView:

LRESULT CmytestDlg::OnRefreshAsyncView(WPARAM wParam, LPARAM lParam)
{
    // For the purpose of a minimal demo, even if this is empty It still casuses the issue.
    return 0;
}

I believe that the issue is triggered by the call to PostMessage, if I comment out this line, I no longer get the crash.

How do I safely handle the scenario where the dialog is closing? So I can prevent this crash.



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)