Archived Forum Post

Index of archived forum posts

Question:

Async task Cannot pass a GCHandle across AppDomains exception when running unit test

Sep 23 '15 at 12:29

C# vs 2013. When I try to run the following code in a unit test, I get the following exception. Any ideas why?

http://www.example-code.com/csharp/async_task.asp

System.ArgumentException was unhandled Message: An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Cannot pass a GCHandle across AppDomains.


Answer

Chilkat stores a reference to the managed object in gcroot in cli (native code) for event callbacks. In a normal synchronous call, this is on the stack and the reference is destructed when the method returns. In the async case, the gcroot survives while the task is running. I suspect this is related to the problem.

In order to have event callbacks, a reference to the object must be stored by the native code, and it must be stored via gcroot. The .NET runtime must know that something is still referencing the managed object. Apparently, gcroot's cannot be used across AppDomains, or maybe there is a workaround -- I'm not sure at this point. (Google search "unmanaged appdomain callback")

I wonder if the unit testing features of Visual Studio are introducing separate AppDomains? This has been tested in Visual Studio by creating a simple forms app..