简体   繁体   中英

Don't know why C# PowerShell Runspace is closing irregularly

I have a MVC web application which shows some information about users in our AD. The AD is synchronized with Office 365, so using the UPN I can retrieve the license information from Office 365 using the Windows PowerShell cmdlets for Office 365 . Basically this all works fine.

As the initialization cmdlet Connect-MsolService takes some time to finish, I'm using kind of a singleton pattern for my Office365Connector class. In my Global.asax in Application_Start() I initialize the singleton instance, in Application_End() I dispose it. The connector class uses exactly one instance of my PowerShellInvoker class which - as the name implies - encapsulates PowerShell invoking. The PowerShell initialization code inside the PowerShellInvoker constructor looks like this:

public PowerShellInvoker(params string[] modules)
{
    var iss = InitialSessionState.CreateDefault();
    iss.ImportPSModule(modules);
    iss.ThrowOnRunspaceOpenError = true;

    _runspace = RunspaceFactory.CreateRunspace(iss);
    _runspace.Open();
    _invoker = new RunspaceInvoke(_runspace);
}

The Office365Connector class calls this constructor with "MSOnline" as parameter. The MSOnline module contains the cmdlets for Office 365. I keep the _runspace and _invoker fields for command execution at a later time. Both fields will be disposed in the Dispose method of PowerShellInvoker (which is called when the Office365Connector class is being disposed). Script execution is done by this line of code:

_invoker.Invoke(scriptText);

So much for the introduction - now here comes the real problem:

In my application, I have a user list. When I click a user, additional information is loaded using an AJAX request. Within this request, my app uses the singleton instance of the Office365Connector class to retrieve the license information for the user. In most cases, this all works perfectly. But sometimes the AJAX request ends up with a code 500. Debugging my source code, I stumbled upon an Exception being thrown in the PowerShellInvoker on the "Invoke" line above, telling me that the Runspace is not open anymore, and I can't figure out why. I can't even really reproduce it. Sometimes, the error occurs when I click the second user. Sometimes, the error occurs on the 10th or 15th user. I already thought about some weird clean-up, timeout or garbage collection techniques used by MVC, but I haven't come to a conclusion. IMHO, the Runspace closing can't be time-based because the time between the "user clicks" is just a few seconds.

The Connect-MsolService cmdlet creates a connection to Office 365, but it doesn't return anything. So re-creating the Runspace if needed is not a work-around because this would be done by the PowerShellInvoker class and the Office365Connector wouldn't know that it has to reconnect to Office 365. (Also this would not solve the problem.) Combining the two classes isn't a solution either because the PowerShellInvoker is also used elsewhere.

So can anyone tell me how to prevent the Runspace from closing or why it is closed?

Edit: More code

The full PowerShellInvoker class can be found here .

In the Office365Connector class, there is currently much overhead. Here are some snippets:

Initialization in constructor:

var cred = new PSCredential(adminUpn, adminPassword);

_psi = new PowerShellInvoker("MSOnline");
_psi.ExecuteCommand("Connect-MsolService", new { Credential = cred });

Method to retrieve the license for a UPN:

public IEnumerable<string> GetUserLicenses(string upn)
{
    PSObject[] licenses = _psi.ExecuteScript(string.Format("(Get-MsolUser -UserPrincipalName \"{0}\").Licenses | % {{ $_.AccountSkuId }}", upn)).ToArray();

    // no licenses: a list with one element (which is null) is returned.
    if (licenses.Length == 1 && licenses[0] == null)
    {
        licenses = new PSObject[0];
    }

    return licenses.Select(pso => pso.ToString()).ToList();
}

As you can see, I added some ToList s to the method return values (especially in the PowerShellInvoker ). I did this because I wanted to prevent lazy execution of the enumerables because I thought this could be the reason for the closed Runspace.

OK, this was a stupid mistake by myself - although I don't really understand why MVC is doing this:

In one of my many attempts to solve the problem I moved the disposal code of my Office365Connector to the Dispose method of the application (in Global.asax.cs ). After that I apparently fixed the original error but it didn't work out because of the disposal stuff. Apparently the application instance is disposed more often than it is "ended". When I moved the code back to Application_End() where it belongs everything worked fine.

That makes my original question kind of invalid because I wrote that my dispose code already was in Application_End() . :-\\

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