If the unmanaged code requires multiple calls to the delegate in the managed code, save the delegate as a member variable.

Source: Internet
Author: User

If the unmanaged code needs to call the callback in the managed code multiple times, save the reference of the delegate as a member variable. Otherwise, an exception similar to the following occurs:

CallbackOnCollectedDelegate Detected
Message: For "Demo! SomeNamespace. SomeClass + SomeDelegate: Invoke "type of garbage collection delegate for callback. This may cause application crash, damage, and data loss. When delivering delegates to unmanaged code, managed applications must keep these delegates active until you are sure they will not be called again.

If the new delegate is referenced with a local variable instead of a member variable, the initial callback of the unmanaged code may be OK, however, the exception mentioned above will occur next, because GC destroys the local variables and the delegate objects referenced by the local variables, when the unmanaged code accesses the function pointer again, the address pointed to by the pointer is invalid.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.