locked
CreateFileAsync failed and StorageFile is null

    Question

  • hello

    my class has a member variable

            Windows::Storage::StorageFile ^ m_file;

    here my code who fails. Sometime CreateFileAsync failed and my member variable m_file is null. why ?

    void BlankApp1::MainPage::btnCreate_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        this->txtFileBox->Text = "Create";
        
        create_task(KnownFolders::PicturesLibrary->CreateFileAsync("text1.txt", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ f)
        {
            this->m_file = f;
        });

        if (this->m_file == nullptr)
        {
            this->txtFileBox->Text = "m_file is nullptr";
            return;
        }
    }


    Christophe Pichaud



    Saturday, December 28, 2013 8:09 PM

Answers

  • I may be reading the braces wrong, but it looks like you're checking m_file outside of the CreateFileAsync's then clause. This is a race condition: there is no guarantee which will run first, and I'd actually expect the then clause to run after more often than not.

    You should move the code which depends on the completion into the then handler.

    --Rob

      
    Saturday, December 28, 2013 8:16 PM
    Owner

All replies

  • I may be reading the braces wrong, but it looks like you're checking m_file outside of the CreateFileAsync's then clause. This is a race condition: there is no guarantee which will run first, and I'd actually expect the then clause to run after more often than not.

    You should move the code which depends on the completion into the then handler.

    --Rob

      
    Saturday, December 28, 2013 8:16 PM
    Owner
  • OK it works !

    void BlankApp1::MainPage::btnCreateWrite2_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        this->txtFileBox->Text = "Create";

        create_task(KnownFolders::PicturesLibrary->CreateFileAsync("text2.txt", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ f)
        {
            this->m_file = f;
            String ^ name = m_file->Name;

            create_task(FileIO::WriteTextAsync(m_file, "hello world")).then([this](task<void> task)
            {
                task.get();
            });
        });

        this->txtFileBox->Text = "Create & WriteFile 2";
    }


    Christophe Pichaud

    Sunday, December 29, 2013 9:59 AM