2013-03-13 202 views
0

當我嘗試使持久性句柄變弱時,爲什麼WeakReferenceCallback未被調用?請參見下面的示例:V8:爲什麼WeakReferenceCallback沒有被調用?

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(); 
} 

回答

0

我認爲有兩個問題:

  1. 你處置弱手柄V8有機會來調用回調之前。你需要在裏面調用的回調。
  2. V8在執行GC之前不會調用弱句柄回調。

試試這個:

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 
} 
+0

謝謝,這確實起作用。我之前的印象是,在調用回調之前,我需要在Persistent句柄上調用Dispose(即釋放強引用)。但現在它是有道理的。當我使它變弱時,我發佈了強烈的參考,噢! – pdizzle 2013-03-13 16:38:52

相關問題