簡體   English   中英

ASP.NET核心APi中的CSharpScript內存泄漏

[英]CSharpScript memory leaks in ASP.NET core APi

我有一個ASP核心API。 一條路由可以從數據庫中執行幾個c#腳本,以在相同的上下文/全局變量上獲得一些計算結果。

所以我有這段代碼:

    public static async Task<FormulaEvalException> TryEvalAsync<T>(this T formulaContext) where T : FormulaContext
    {
        FormulaEvalException res = null;
        ScriptState state = null;
        var scriptOptions = ScriptOptions.Default.WithReferences("System", "System.Linq", "System.Globalization", "Microsoft.CSharp").WithImports(new[] { "System", "System.Linq", "System.Math", "System.Globalization", "System.Collections.Generic" });
        foreach (var formulaList in formulaContext.AllFormulas.Values)
        {
            foreach (var formula in formulaList)
            {
                formulaContext.CurrentFormula = formula;
                try
                {
                    if (state == null)
                    {
                        state = await CSharpScript.RunAsync(formula.Script, scriptOptions, formulaContext);
                    }
                    else
                    {
                        state = await state.ContinueWithAsync(formula.Script);
                    }
                    var result = state.ReturnValue;
                    if (result == null)
                    {
                        if (res == null)
                        {
                            res = new FormulaEvalException(formula.Title + " : No result");
                        }
                        continue;
                    }

                    formula.Result = result;
                }
                catch (CompilationErrorException ex)
                {
                    if (res == null)
                    {
                        res = new FormulaEvalException(formula.Title + ex.Message);
                    }
                    continue;
                }
                catch
                {
                    continue;
                }
            }
        }

        return res;
    }

此代碼導致我內存泄漏,用戶無法重復這些請求。

從以前的搜索中,我得到了一些信息,作為我的FormulaContext類與位於另一個項目中有關。 因此,我將其放在API項目之外的模型項目中。 但是我仍然有這個問題。

我嘗試了幾種執行腳本的方法(例如,使用CSharpScript.Create或CSharpScript.EvaluateAsync),但是仍然沒有釋放內存。

我還聽說了AppDomain類,可以在使用后在沙箱中執行腳本並釋放內存,但在ASP.NET Core中不再使用AppDomain。

謝謝你的幫助 ;)

好的,我找到了解決方法:

                finally
                {
                    GC.Collect();
                }

內存從1 GB以上降至250 MG。 我知道,一旦加載了類型或程序集,就無法再將其卸載,但是公式很小,因此我想由於CSharpScript的編譯過程,我的內存已滿。

我現在正在等待卸載程序集的能力,以徹底清理該程序集。 顯然是有計划的: https : //github.com/dotnet/coreclr/issues/552

感謝曾先生的幫助。

你們為什么要跳這么多。 DotNet Core不支持程序集/類型的卸載,並且直到3.0才會卸載。

我正在為DotNet Core開發CMS / VFS,這是目前最大的障礙。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM