简体   繁体   English

C#SQLite Windows CE“内存不足异常”。

[英]C# SQLite Windows CE “Out of memory exception.”

So I keep having a problem where I'm getting an error stating I'm out of memory. 所以我一直遇到问题,指出我的内存不足。 I have a main thread and a worker thread that uses a file called SqlLiteAssetCommands.cs which contains some commands such as the following. 我有一个主线程和一个工作线程,该线程使用名为SqlLiteAssetCommands.cs的文件,其中包含一些命令,例如以下命令。

    Database newConnection;
    /// <summary>
    /// Open connection return the SQLlight command
    /// </summary>
    /// <returns></returns>
    private SQLiteCommand openConnection()
    {
        newConnection = new Database();
        SQLiteCommand command = new SQLiteCommand();
        try
        {
            newConnection.OpenConnection();
            command = newConnection.Connection.CreateCommand();
        }
        catch (Exception e)
        {
            log.Error("Could not open connection.", e);
        }
        return command;
    }

    /// <summary>
    /// Close connection to the local database.
    /// </summary>
    private void closeConnection()
    {
        try
        {
            newConnection.CloseConnection();
        }
        catch (Exception e)
        {
            log.Error("Could not close the connection.", e);
        }
    }

    /// <summary>
    /// Creates a transaction.
    /// </summary>
    /// <returns>Returns the new transaction that is created.</returns>
    private SQLiteTransaction getTransaction()
    {
        SQLiteTransaction sqlTransaction = null;
        try
        {
            sqlTransaction = newConnection.Connection.BeginTransaction();
        }
        catch (Exception e)
        {
            log.Error("Could not get sqlTransaction.", e);
        }
        return sqlTransaction;
    }

    #region Asset Database commands

    /// <summary>
    /// Delete all rows from sqlite database.
    /// </summary>
    /// <returns>Returns "Completed" if successful.</returns>
    public String deleteAllRows()
    {
        SQLiteCommand command = openConnection();
        String status = null;
        using (SQLiteTransaction sqlTransaction = getTransaction())
        {
            try
            {
                command.CommandText = @"DELETE FROM Asset";
                using (SQLiteDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        reader.Read();
                    }
                    reader.Close();
                }
                status = "Completed";
                sqlTransaction.Commit();
            }
            catch (Exception e)
            {
                log.Error("Could not delete all assets.", e);
            }
        }
        closeConnection();
        return status;
    }

So my open connection is called from a different file called Database.cs and the error is caught on the open function stating I'm out of memory. 因此,我的打开连接是从另一个名为Database.cs的文件中调用的,并且该错误在打开函数中显示,提示我内存不足。 I'm not sure what I need to do to keep this from happening as I cannot force the error to occur. 我不确定该怎么做才能阻止这种情况的发生,因为我无法强迫错误发生。 This time happened when I was trying to force an error to show so I could screen-shoot it and finally got tired of trying and waited without doing anything. 这一次发生在我试图强制显示错误时,我可以对其进行屏幕截图,最后又厌倦了尝试并等待而无所事事。 Then it just happened due to my worker thread. 然后由于我的工作线程而发生了。

    public SQLiteConnection Connection = new SQLiteConnection();
    // Define a static logger variable so that it references the name of your class
    private static readonly ILog log = LogManager.GetLogger(typeof(Database));

    // Try to open a connection to the sqlLight database.
    public void OpenConnection()
    {
        try
        {
            Connection = new SQLiteConnection("Data Source=" + Utilities.Global.SqlLiteDB);
            Connection.Open();
        }
        catch (Exception eErr)
        {
            log.Error("Error connecting to database.", eErr);
            MessageBox.Show("Error connecting to database.", "Error", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
        }
    }
    // Close the database connection.
    public void CloseConnection()
    {
        Connection.Close();
    }
}

在此处输入图片说明

Anything I can do to fix this or improve my code would be helpful. 我可以采取任何措施解决此问题或改进我的代码,这将对您有所帮助。

Here is the code for my worker thread since this may be the root cause of the problem. 这是我的工作线程的代码,因为这可能是问题的根本原因。

class AssettoServerThread
{
    // Define a static logger variable so that it references the name of your class
    private static readonly ILog log = LogManager.GetLogger(typeof(AssettoServerThread));

    WebServicesSyncAsset syncAsset = new WebServicesSyncAsset();
    SqlLightAssetCommands assetToSql = new SqlLightAssetCommands();


    /////////////////////// Variables //////////
    private volatile bool _shouldStop = false;

    // SINGLETON ///////////////////////////////
    private static AssettoServerThread instance = null;

    public static AssettoServerThread GetInstance()
    {
        if (instance == null)
            instance = new AssettoServerThread();

        return instance;
    }
    // /////////////////////////////////////////

    // this variable will hold the condition of ServicesAvailable set by the worker thread
    private bool areServicesAvailable = false;

    private bool AreServicesAvailable
    {
        get { return areServicesAvailable; }
        set { areServicesAvailable = value; }
    }

    // This method will be called when the thread is stopped. 
    public void RequestStop()
    {
        _shouldStop = true;
    }

    // Create a worker thread and then check if the webservices are available.
    // If available then set ServicesAvailable to true and begin sending updated assets to the server.
    public void DoThreading()
    {
        // Continuous loop
        while (!_shouldStop)
        {
            try
            {
                // Creates an HttpWebRequest for the specified URL.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AppConfigSettings.serverIP);
                // Set some reasonable limits on resources used by this request
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                // Sends the HttpWebRequest and waits for a response.
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    //request.Abort();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        areServicesAvailable = true;
                    }
                    // Releases the resources of the response.
                    response.Close();
                }
            }
            catch (WebException ex)
            {
                areServicesAvailable = false;
                log.Info("Website is currently not accessible. Therefore the services are not accessible.", ex);
            }
            catch (Exception ex)
            {
                areServicesAvailable = false;
                log.Info("Website is currently not accessible. Therefore the services are not accessible.", ex);
            }

            // If the webservices are available then run else sleep for 30 seconds.
            if (AreServicesAvailable)
            {
                try
                {
                    assetToSql.AddAssetsToServer();
                    Thread.Sleep(2000);
                }
                catch (Exception e)
                {
                    log.Error("Could not add asset to server.", e);
                }
            }
        }
    }
}

Then it just happened due to my worker thread. 然后由于我的工作线程而发生了。

Your threading code might be relevant, then. 然后,您的线程代码可能是相关的。

What I ended up doing was instead of having two threads I made it into one worker thread and made sure it never overlapped. 我最终要做的是将两个线程变成一个工作线程,并确保它从不重叠,而不是使用两个线程。 I also added a connection pool to my SQLlite database. 我还向我的SQLlite数据库添加了一个连接池。 I also changed the images on my project and deleted all unnecessary images to save space. 我还更改了项目中的图像,并删除了所有不必要的图像以节省空间。 I don't know what fixed it but this worked for me. 我不知道是什么解决了这个问题,但这对我有用。

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

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