1

在给定用例的情况下,我的印象是对 WinRT 对象的引用计数是线程安全的。但是我遇到了一个我不知道任何其他方式来解释的错误。例如,以下代码很快崩溃:

ref class C sealed {
public:
    C() { }
    virtual ~C() {}
};

[Windows::Foundation::Metadata::WebHostHidden]
public ref class MainPage sealed {
public:
    MainPage() : _latest(nullptr) {
        InitializeComponent();
        Windows::System::Threading::ThreadPool::RunAsync(
            ref new Windows::System::Threading::WorkItemHandler(
                this, 
                &MainPage::SetLatest));
        Windows::System::Threading::ThreadPool::RunAsync(
            ref new Windows::System::Threading::WorkItemHandler(
                this, 
                &MainPage::OnRendering));
    }
    virtual ~MainPage(){}
private:
    C^ _latest;
    void SetLatest(Windows::Foundation::IAsyncAction^ operation){
        while (true) {
            _latest = ref new C(); 
        }
    }
    void OnRendering(Windows::Foundation::IAsyncAction^ operation) {
        while (true) {
            auto c = _latest;
        }
    }
};

当读/写竞速时, WinRT 指针(即 ref 类类型C^)是否应该被正确引用计数?是否有一个我不知道的单独问题导致了这次崩溃?

4

1 回答 1

6

ref class对象引用计数的更改是同步的,但对T^对象的更改不是。

您有两个线程_latest同时访问,其中一个线程正在修改_latest,因此您需要同步访问_latest,例如使用std::mutex.

于 2012-08-31T12:06:46.383 回答