V8:为什么不调用WeakReference回调?

时间:2013-03-13 01:27:58

标签: javascript v8

当我尝试使持久句柄变弱时,为什么不调用WeakReference回调?请参阅以下示例:

void myWeakReferenceCallback(v8::Persistent<v8::Value> theValue, void *theParameter)
{
    fprintf(stdout, "myWeakReferenceCallback");
}

void testWeakReferenceCallback()
{
    v8::Persistent<v8::Value> persistent_value;
    {
        v8::Persistent<v8::Context> context = v8::Context::New();
        v8::Context::Scope context_scope(context);
        v8::HandleScope handle_scope;
        v8::Local<v8::Value> local_value = v8::NumberObject::New(5.0);
        persistent_value = v8::Persistent<v8::Value>::New(local_value);
        persistent_value.MakeWeak(NULL, myWeakReferenceCallback);
        context.Dispose();
    }
    persistent_value.Dispose();
}

1 个答案:

答案 0 :(得分:0)

我相信有两个问题:

  1. 在V8有机会调用回调之前,你正在处理弱句柄。您需要将内部处理回调。
  2. V8在执行GC之前不会调用弱句柄回调。
  3. 试试这个:

    void myWeakReferenceCallback(v8::Persistent<v8::Value> theValue, void *theParameter)
    {
        fprintf(stdout, "myWeakReferenceCallback");
        theValue.Dispose();
    }
    
    void testWeakReferenceCallback()
    {
        v8::Persistent<v8::Value> persistent_value;
        {
            v8::Persistent<v8::Context> context = v8::Context::New();
            v8::Context::Scope context_scope(context);
            v8::HandleScope handle_scope;
            v8::Local<v8::Value> local_value = v8::NumberObject::New(5.0);
            persistent_value = v8::Persistent<v8::Value>::New(local_value);
            persistent_value.MakeWeak(NULL, myWeakReferenceCallback);
            context.Dispose();
        }
        //persistent_value.Dispose();
        while (!v8::V8::IdleNotification()); // force GC
    }