简体   繁体   中英

IIS application pool recycling and native assemblies

I have an application that runs under IIS, the application has three assemblies: a managed assembly, a mixed assembly and a native dll. The managed assembly exposes a singleton object MaS that wraps a native singleton NaS via a mixed singleton MiS (C++/CLI).

PROBLEM

When IIS recycles the application pool, the managed singleton MaS seem to go away and its assembly unloaded from the APPDOMAIN and so does the mixed one MiS . However, the native singleton NaS sticks around and does not get destroyed. This is problematic in my case as when the application is recycled and loaded again, the managed singleton, now MaS1 gets confused as it finds an already existing native singleton NaS in memory.

QUESTION

How are native dlls handled at application pool recycles? Do they get unloaded?

Appdomain recycling does not unload appdomain, it loads a new domain, and subsequent requests are handled by a new appdomain.

Old appdomain unloads only when finished processing the already accepted requests.

It's also possible that an old appdomain fail to unload if it performs a blocking operation in unmanaged code.

As a workaround you could disable apppool recycle and configure ovelapping worker processes. Separate worker process will isolate the unmanaged dll state for sure.

You can easily check that unmanaged dll has it's state shared between appdomains with following code:

Managed code:

[DllImport("Win32Library.dll")]
public static extern Int16 inc();

private readonly static DateTime AppDomainStarted = DateTime.UtcNow;

public ActionResult Counter()
{
    return new JsonResult { Data = new { counter = inc(), appDomainId = AppDomain.CurrentDomain.Id, started = AppDomainStarted.ToString() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Unmanaged code:

extern "C" __declspec(dllexport) short inc();

short inc()
{
    static int counter = 0;
    return counter++;
}

Just recompile your aspnet code and refresh browser to see incrementing result in counter, and appdomain id inside the working process. Make sure you use IISExpress for debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM