Memory leaks in C# hosted Powershell

  • Thread starter Thread starter Karel Pokorny
  • Start date Start date
K

Karel Pokorny

Guest
Hi,

i have a simple app, that's creating a Powershell runspace:

var iis = InitialSessionState.CreateDefault();
iis.ExecutionPolicy = ExecutionPolicy.Unrestricted;
iis.LanguageMode = PSLanguageMode.FullLanguage;
iis.ThreadOptions = PSThreadOptions.UseNewThread;
iis.DisableFormatUpdates = true;

m_Settings = new PSInvocationSettings
{
Host = new PSHostProxy(new PSUIStub()),
};

m_RunspacePool = RunspaceFactory.CreateRunspacePool(iis);
m_RunspacePool.CleanupInterval = new TimeSpan(0, 0, 10);
m_RunspacePool.SetMaxRunspaces(1);
m_RunspacePool.SetMinRunspaces(1);
m_RunspacePool.Open();



And then uses it to execute several PowerShell scripts. Each RUN is invoked by external event (runs in another thread) and happens ussualy with 20-50 seconds after the foregoing RUN:

RUN:
{
foreach(var scriptName in scripts)
{
var ps = PowerShell.Create();
ps.RunspacePool = m_RunspacePool;
var input = new PSDataCollection<string>();

ps.AddCommand(Path.Combine(scriptPath, scriptName));
ps.AddArgument(args);

// Call
ps.Invoke(input, m_Output, m_Settings);
...
m_Output.Clear();
input.Clear();
input.Dispose();

ps.Dispose();
ps = null;
}
}

And memory usage of this keeps raising during the run, although the scripts are always the same and even their results are the same. Each cycle creates a bunch (well like thousands of them, but i suppose the number is given by length of the executed scripts...) of SessionStateCmdLetEntry and those are never disposed and GCed, because of reference by a TimerCallback created by RunspacePoolInternal. This can take up to 1GB of memory per day...

Does anyone have tips, what else should I dispose or clear to avoid stashing the SessionStateCmdLetEntries? Or any workarounds for this?

I just need a long running process, that invokes several Powershell scripts and does not eat up memory.. I've also tried not reusing the RunSpacePool and creating a new Runspace for each RUN and even for each script, but it did not help at all...


Thanks for any help...

Continue reading...
 

Similar threads

C
Replies
0
Views
101
Carlo Goretti
C
C
Replies
0
Views
142
Carlo Goretti
C
C
Replies
0
Views
335
Carlo Goretti
C
C
Replies
0
Views
303
Carlo Goretti
C
Back
Top