C#数据库连接类中的ObjectDisposedException

我是C#的新手,我正在c#中编写一个需要连接sqlite数据库的应用程序。我认为创建我自己的DBConnection课程对我来说是最简单的,下面将对此进行介绍。我目前遇到的主要问题是析构函数。有时,当我实例化该类并且超出范围时,我得到一个


System.ObjectDisposedException; '无法访问已处置的对象。对象名称:“ SQLiteConnection”。


现在,我已经搜索了这意味着什么的定义,但是我不太了解。


该对象将作为wpf应用程序窗口的一部分进行实例化,并且在窗口x退出后以及数据库操作完成后,将引发此异常。


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Data.SQLite;

using System.IO;


namespace PhotoSuppliesInc

{

    //this class will be used for connecting to the database in the various forms

    public class DBConnector

    {

        //----------------------------------PRIVATES------------------------------//

        //this is the connection to the db

        private SQLiteConnection dbConnection;


        //-------------------CONSTRUCTOR(S) and DESCTRUCTOR----------------//

        public DBConnector()

        {

            string connectionString = "Data Source=C:\\Users\\dmand\\source\\repos\\PhotoSuppliesInc\\PhotoSuppliesInc\\database\\riverfrontphoto.db;" +

                                            "Version = 3; FailIfMissing=True; Foreign Keys=True;";

            try

            {

                dbConnection = new SQLiteConnection(connectionString);

                dbConnection.Open();

                MessageBox.Show("Database connected successfully");

            }//end try

            catch (SQLiteException e) { MessageBox.Show("error opening database"); }

        }//end constructor

        //destructor removes connection to database

        ~DBConnector()

        {

                dbConnection.Close();

        }

        //--------------------------------------------------GETTER(S)------------------------//

        //public string Get_Filepath() { return filepath; }


        //--------------------------------------------------UTILITY FUNCTIONS----------------//


如我所说,我不知道此错误的含义,或者我是否正确使用了这种语言的析构函数。在我看来,这里应该没有问题。有人可以帮我弄清楚这个错误在班上意味着什么吗?谢谢大家的时间。


蝴蝶刀刀
浏览 359回答 1
1回答

holdtom

您没有正确使用“析构函数”,因为C#没有析构函数,它具有终结器。执行您要执行的操作的正确方法是实现IDisposable模式并在using块中访问类的实例。终结器(由〜语法表示)是不确定的-您无法控制垃圾收集器何时运行终结器,或者是否运行终结器。IDisposable在using块中实现和访问实例可让您实现确定性的资源清理。这就是为什么您得到的原因ObjectDisposedException:处置您的类之后,您的类的终结器正在运行SQLiteConnection。
打开App,查看更多内容
随时随地看视频慕课网APP