为什么会抛出 "read access violation"?

Why is this throwing "read access violation"?

现在我试图在读取和处理文件时显示进度条对话框,但我的代码在关闭对话框时抛出 "read access violation"。

确切的错误信息是,

**__pUnknown** was 0xFFFFFFFFFFFFFFFF.

下面是我的代码。

void LoadFile(StorageFile^ file) {
    ContentDialog^ loaderDialog = ref new ContentDialog();
    loaderDialog->Title = L"Loading...";
    loaderDialog->Content = ref new ProgressBar();
    loaderDialog->ShowAsync();

    Concurrency::create_task(FileIO::ReadTextAsync(file))
        .then([&](Platform::String^ fileText) {

            // File processing parts are omitted.
            // ...

            loaderDialog->Hide(); // Read access violation!
        }
    );
}

为什么这会变成错误?

发件人:https://devblogs.microsoft.com/cppblog/ccx-part-2-of-n-types-that-wear-hats/

So, what exactly is a ^ type? A hat type is a smart pointer type that (1) automatically manages the lifetime of a Windows Runtime object and (2) provides automatic type conversion capabilities to simplify use of Windows Runtime objects.

您正在对智能指针进行引用,因此您没有增加其引用计数,请参阅 https://docs.microsoft.com/en-us/windows/win32/com/rules-for-managing-reference-counts 。 这意味着当继续执行时,引用是悬空的。

您可以尝试按值 [=] 而非引用 [&] 进行捕获。 请注意,您应该考虑在捕获中捕获每个变量,而不是使用 [=][&]