简体   繁体   English

asp.net MVC应用程序中的文件读写内存泄漏

[英]file read write memory leak in asp.net mvc application

Intailly I read the json string from text file and converting the json string to object and add it to the list. 我确实从文本文件中读取json字符串,并将json字符串转换为object并将其添加到列表中。 Then I am calling the instagram feed API in loop, after getting the response I am converting the response string to json object and add it to list. 然后我循环调用instagram feed API,获得响应后,我将响应字符串转换为json对象,并将其添加到列表中。 Finally I am converting the list of objects to json string and write it to the text file. 最后,我将对象列表转换为json字符串并将其写入文本文件。

I need to update the json string in two text files, so after completing all the request to instagram, I am copying the json string from one text file to another text file. 我需要在两个文本文件中更新json字符串,因此在完成对instagram的所有请求后,我将json字符串从一个文本文件复制到另一个文本文件。

My problem 我的问题

I am calling this InstagramRecentList method in every 10 minutes to reflect the recent instagram feeds in my web site. 我每10分钟调用一次InstagramRecentList方法,以反映我网站上最近的instagram feed。 When I check the Memory usage in server, this application pool occupy more memory also in one stage all the apps hosted in IIS stops wroking because of this. 当我检查服务器中的内存使用情况时,此应用程序池还会在一个阶段占用更多内存,因此,IIS中托管的所有应用程序都将停止运行。 What is the best and efficient way to do above process so that my application do not occupy more memory. 什么是最好的和有效的方法来完成上述过程,以便我的应用程序不占用更多的内存。

Here is the screen shot with the selected process shows memory usage of that application pool, as of now i am recycling the app pool every day. 是选定进程的屏幕快照,显示了该应用程序池的内存使用情况,截至目前,我每天都在回收该应用程序池。 If I stop recycling the app pool, the memory usage get increased. 如果我停止回收应用程序池,则内存使用量会增加。 Please help me. 请帮我。 Sorry for my English. 对不起我的英语不好。

public ActionResult InstagramRecentList()
{
    string filepath = Path.Combine(ConfigurationManager.AppSettings["instgramfilepath"], Constants.w_Instagram_recent_listJsonFile);

    string ClientId = ConfigurationManager.AppSettings["instgramclientid"];
    string HondaId = ConfigurationManager.AppSettings["instgramhondaid"];
    WriteInstagramRecentList(filepath, HondaId, ClientId);
    string wp = Path.Combine(ConfigurationManager.AppSettings["instgramfilepath"], Constants.r_Instagram_recent_listJsonFile);
    string Jsonstring = String.Empty;
    using (StreamReader sr = System.IO.File.OpenText(filepath))
    {
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
            Jsonstring = Jsonstring + s;
        }
    }

    TextWriter tw = new StreamWriter(wp);
    tw.WriteLine(Jsonstring);
    tw.Close();
    tw.Dispose();
    return View("UpdateResult");
}

private static void WriteInstagramRecentList(string filepath, string HondaId, string ClientId, string nextpageurl = null)
{
    string feedurl = string.Empty;
    List<object> modeldata = new List<object>();
    if (nextpageurl != null)
    {
        feedurl = nextpageurl;

        string Jsonstring = String.Empty;
        using (StreamReader sr = System.IO.File.OpenText(filepath))
        {
            string s = String.Empty;
            while ((s = sr.ReadLine()) != null)
            {
                Jsonstring = Jsonstring + s;
            }
        }
        if (!string.IsNullOrEmpty(Jsonstring))
        {
            modeldata = JsonConvert.DeserializeObject<List<object>>(Jsonstring);
        }
    }
    else
    {
        feedurl = String.Format("https://api.instagram.com/v1/users/{0}/media/recent/?client_id={1}&count={2}", HondaId, ClientId, 200);
    }

    var request = WebRequest.Create(feedurl);
    request.ContentType = "application/json; charset=utf-8";
    string text;
    var response = (HttpWebResponse)request.GetResponse();
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        text = reader.ReadToEnd();
        if (!string.IsNullOrEmpty(text))
        {
            dynamic result = System.Web.Helpers.Json.Decode(text);
            if (result.data != null)
            {
                modeldata.AddRange(result.data);
            }
            string json = JsonConvert.SerializeObject(modeldata);
            TextWriter tw = new StreamWriter(filepath);
            tw.WriteLine(json);
            tw.Close();
            tw.Dispose();
            if (result.pagination != null && !string.IsNullOrEmpty(result.pagination.next_url) && modeldata.Count < 205)
            {
                WriteInstagramRecentList(filepath, HondaId, ClientId, result.pagination.next_url);
            }

        }
    }
}

Do not ever use the string class directly when concatenating strings. 连接字符串时,切勿直接使用string类。 They are immutable in C# (as in many other languages). 它们在C#中是不变的(与许多其他语言一样)。 This means that you are creating a new string each time. 这意味着您每次都在创建一个新字符串。 Use the StringBuilder class instead, and don't create a copy of each line - check EndOfStream property instead: 请改用StringBuilder类,并且不要创建每行的副本-而是检查EndOfStream属性:

StringBuilder jsonString = new StringBuilder;
using (StreamReader sr = System.IO.File.OpenText(filepath))
{
    while (!sr.EndOfStream))
    {
        jsonString.AppendLine(sr.ReadLine());
    }
}

Or simply use the ReadToEnd method of the StreamReader class: 或者简单地使用StreamReader类的ReadToEnd方法:

String jsonString = String.Empty;
using (StreamReader sr = System.IO.File.OpenText(filepath))
{
     jsonString = sr.ReadToEnd();
}

You can combine these methods too. 您也可以结合使用这些方法。 Another thing that you should check when working with graphics - are you creating some images according the response of Instagram? 使用图形时应检查的另一件事-是否根据Instagram的响应创建一些图像? If so, consider disposing them after use. 如果是这样,请考虑在使用后丢弃它们。 You can use the using pattern on the TextWriter object too, like this: 您也可以在TextWriter对象上使用using模式,如下所示:

using (TextWriter tw = new StreamWriter(wp))
{
    tw.WriteLine(Jsonstring);
}

Putting it all together, you can rewrite your method as such: 放在一起,您可以这样重写方法:

using (StreamReader sr = System.IO.File.OpenText(filepath))
using (TextWriter tw = new StreamWriter(wp))
{
    tw.WriteLine(sr.ReadToEnd());
}

My first suggestion is - try to avoid recursive call of the 我的第一个建议是-尽量避免递归调用
WriteInstagramRecentList method. WriteInstagramRecentList方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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