none
asp.net 多线程的访问数据库的数据安全问题 RRS feed

  • 问题

  • 如题,asp.net 中在Global.asax中启动一个线程,这个线程中会读取数据库中数据放入一个Dataset中然后对Dataset中的数据作处理后发送给某硬件终端设备。

    问题是在线程运行时会出现报Dataset未将对象实例化,且此事所有页面读取数据库数据的地方都出现异常。现在实在不知道是什么地方出了问题


    pinkbull

    2013年11月13日 14:34

全部回复

  • 可以给出你完整的代码吗?谢谢!

    For Account Validation, please follow "Verify Account+Number" at http://social.msdn.microsoft.com/Forums/en-us/home?forum=reportabug

    For ASP.NET Question, please ask at http://forums.asp.net

    For other questions, you can find a specific forum and then ask at http://stackexchange.com/sites

    Click and Donate at http://www.freerice.com

    2013年11月14日 2:58
  • 你好,

         你可以看下这个链接,希望可以帮到你:

          ASP.net:在多线程里查询数据库并填充dataGrid

          http://blog.sina.com.cn/s/blog_83b447810100u44c.html


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click <a href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

    2013年11月15日 5:33
    版主
  • 已下是Global.asax的代码,主要流程是在Application_Start中启动一个线程循环读取数据库数据已设置的间隔时间是否等于允许时间,相同则启动一个线程读取数据库人员资料表并处理后传给硬件控制器。
    void Application_Start(object sender, EventArgs e)
        {
     System.Threading.Thread cogradienting=
            // 在应用程序启动时运行的代码
            if (cogradienting == null)
            {
                cogradienting = new System.Threading.Thread(new System.Threading.ThreadStart(synchro_personal));
                if (!cogradienting.IsAlive)
                {
                    cogradienting.Start();
                }
                Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                logfile.WriteFile(str, Shorttim + "启动");
            }
            else if (!cogradienting.IsAlive)
            {
                cogradienting.Start();
            }
    
        }
        /// <summary>
        /// 此方法是一个循环读取数据库数据根据设置的时间间隔启动另一个线程操作相关事务
       ///
        /// </summary>
     public void synchro_personal()
        {
            string time1 = "0";
            string time2 = "0";
            int tmptime = 1;
            while (boolthread)
            {
                try
                {
                    lock (syncRoot)
                    {
                        mj_zk zk = new mj_zk();//数据库操作类
                        System.Data.DataTable dt = new System.Data.DataTable();
                        dt = zk.ZK_1().Tables["Mj_ZK"];//读取数据库数据, 见下 面mj_zk类
                        time1 = dt.Rows[0]["mj_zk_b4"].ToString();
                        if (time1 != time2)
                        {
                            time2 = time1;
                            tmptime = 1;
                        }
                        else
                            if (tmptime == Convert.ToInt32(time1) * 60 && synper.checksyn)
                            {
                                tmptime = 1;
                                synper synp = new synper(TerminalTable);//线程操作类见下面synper类
                                synp.Start();
                            }
                            else if (tmptime == Convert.ToInt32(time1) * 60)
                            {
                                tmptime = 1;
                            }
                    }
    
                }
                catch (Exception ex)
                {
    
                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string str1 = System.AppDomain.CurrentDomain.BaseDirectory + "/log.txt";
                    logfile.WriteFile(str1, Shorttim + ex.Message.ToString() + ";synchro_personal");
             
                }
                tmptime++;
                System.Threading.Thread.Sleep(1000);
    
            }
        }
    
    
    ///mj_zk类
    public class mj_zk
    {
        private string ConfigString;
        private SqlConnection SqlConnTion;
        private SqlCommand SqlCommand;
        private SqlDataAdapter SqlAdter;
        public mj_zk()
        {
            ConfigString = ConfigurationManager.ConnectionStrings["FK_MJConnectionString"].ToString(); 
            SqlConnTion = new SqlConnection(ConfigString);
            SqlCommand = new SqlCommand();
            SqlAdter = new SqlDataAdapter();
        }
      public DataSet ZK_1()
        {
            DataSet Ds = new DataSet();
            try
            {
                SqlAdter.SelectCommand = new SqlCommand("select * from Mj_ZK", SqlConnTion);
                SqlAdter.Fill(Ds, "Mj_ZK");
            }
            catch (System.Exception ex)
            {
                string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string str = System.AppDomain.CurrentDomain.BaseDirectory + "/log.txt";
                logfile.WriteFile(str, Shorttim  + ex);
            }
            return Ds;
        }
    }
    
    
    
    ///synper类
    ///此类中主要是启动一个线程读取数据库人员资料让后通过硬件的sdk接口传给硬件
    
    public class synper
    {
    
        System.Data.DataTable TerminalTable = new System.Data.DataTable();
        public static object syncRoot = new object();
        public static bool checksyn = true;
        string str1 = System.AppDomain.CurrentDomain.BaseDirectory + "log_syn.txt";
    
        public synper(DataTable TerminalTable)
        {
            this.TerminalTable = TerminalTable;
        }
    
        public void Start()
        {
            Thread t = new Thread(cogradient);
            t.IsBackground = true;
            if (!t.IsAlive)
            {
                t.Start();
                checksyn = false;
            }
        }
    
        /// <summary>
        /// 同步人员信息方法
        /// </summary>
        public void cogradient()
        {
            lock (syncRoot)
            {
                CardNoADC cardADC = new CardNoADC();
                logfile.WriteFile(str1, "自动同步开始时间" + syn_time);
                int y_syn_personal_number = 0;//需同步人数
                CLRProfilerControl.LogWriteLine("Entering loop");
                CLRProfilerControl.AllocationLoggingActive = true;
                CLRProfilerControl.CallLoggingActive = true;
                string terminal_id = "0";
                string format = "0";
                syn sy = new syn();//此类与mj_zk类一样是连接数据库并读取数据库数据
                format = sqlconn.format;
                System.Data.DataSet terminalid_ds = new System.Data.DataSet();
                System.Data.DataSet personals_ds = new System.Data.DataSet();
                try
                {
                    personals_ds = sy.selectUppersonal("personals_tb");//获取人员信息
                    y_syn_personal_number = personals_ds.Tables["personals_tb"].Rows.Count;//应同步人数
                }
                catch (Exception ex)
                {
                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    // string str1 = System.AppDomain.CurrentDomain.BaseDirectory + "/log.txt";
                    logfile.WriteFile(str1, Shorttim + "位置:获取同步人员" + ex.Message.ToString());
    
                }
    
                for (int j = 0; j < y_syn_personal_number; j++)
                {
                    string senddatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        string emcode = personals_ds.Tables["personals_tb"].Rows[j]["emcode"].ToString();
                        string emcard = personals_ds.Tables["personals_tb"].Rows[j]["emcard"].ToString();
                        string kxh = personals_ds.Tables["personals_tb"].Rows[j]["emkxh"].ToString();
                        string CardNo = cardADC.switchcard(emcard, kxh, format);
                        string lxo = personals_ds.Tables["personals_tb"].Rows[j]["mj_lx"].ToString();
                        string UserID = personals_ds.Tables["personals_tb"].Rows[j]["per_id"].ToString();
                        string UserName = personals_ds.Tables["personals_tb"].Rows[j]["emName"].ToString();
                        string mj_qz1 = personals_ds.Tables["personals_tb"].Rows[j]["mj_qz1"].ToString();
                        string mj_qz2 = personals_ds.Tables["personals_tb"].Rows[j]["mj_qz2"].ToString();
                        string mj_qz3 = personals_ds.Tables["personals_tb"].Rows[j]["mj_qz3"].ToString();
                        string mj_qz4 = personals_ds.Tables["personals_tb"].Rows[j]["mj_qz4"].ToString();
                        string mj_lv = personals_ds.Tables["personals_tb"].Rows[j]["mj_lv"].ToString();
                        string PersonalPassword = personals_ds.Tables["personals_tb"].Rows[j]["mj_ma"].ToString();
                        string emworkno = personals_ds.Tables["personals_tb"].Rows[j]["emworkno"].ToString();
                        string emstate = personals_ds.Tables["personals_tb"].Rows[j]["emstate"].ToString();
                        string emlz = personals_ds.Tables["personals_tb"].Rows[j]["emlz"].ToString();
    
                        terminalid_ds = sy.g_s_t(mj_qz1, mj_qz2, mj_qz3, mj_qz4, "t_tb");
                        for (int i = 0; i < terminalid_ds.Tables["t_tb"].Rows.Count; i++)
                        {
                            terminal_id = terminalid_ds.Tables["t_tb"].Rows[i]["t_id"].ToString();
                            string ChannelID = sy.selectChannelID(terminal_id, TerminalTable);
                            if (emstate != "0")
                            {
    //此处代码为对硬件操作
                                SemacV14.Request.UserDeletionRequest re = new SemacV14.Request.UserDeletionRequest(Convert.ToInt32(terminal_id), Convert.ToUInt32(UserID));
                                SemacV14.Service.ExecuteArgz Ea = new SemacV14.Service.ExecuteArgz(ChannelID, re);
                                SemacV14.Service.Actor act = new SemacV14.Service.Actor(Ea);    //实例化Actor
                                Ea = act.SendAndReceive();           //发送命令,并返回执行结果。
                                //结果判断
                                if (Ea.IsCompleted == true)
                                {
                                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    logfile.WriteFile(str1, Shorttim + ",工号:" + emworkno + "同步到" + terminal_id + "号控制器销户成功," + Ea.ErrorMessage);
                                    sy.up_mj_p_qz(UserName, kxh, terminal_id, UserID, emcode, mj_qz1, mj_qz2, mj_qz3, mj_qz4, emstate, emlz);
                                }
                                else
                                {
                                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    logfile.WriteFile(str1, Shorttim + ",工号:" + emworkno + "同步到" + terminal_id + "号控制器销户失败," + Ea.ErrorMessage);
    
                                }
                            }
                            else
                            {
    //此else中的代码也是对硬件
                                SemacV14.Request.RegisterModifyUserDataRequest re = new SemacV14.Request.RegisterModifyUserDataRequest(Convert.ToInt32(terminal_id));
                                re.UserID = Convert.ToUInt16(UserID);
                                re.EmployeeID = emworkno;
                                re.CardNo = CardNo;
                                re.UserName = UserName;
                                switch (lxo)
                                {
                                    case "一般用户":
                                        re.UserType = SemacV14.Define.UserType.NormalUser;//一般用户
                                        break;
                                    case "管理者":
    
                                        re.UserType = SemacV14.Define.UserType.SuperUser;//超级用户
                                        break;
                                    case "访客":
    
                                        re.UserType = SemacV14.Define.UserType.Visitor;//访客
                                        break;
                                    case "巡更":
                                        re.UserType = SemacV14.Define.UserType.GuardTouring;//警卫队巡回
                                        break;
                                    case "保全":
                                        re.UserType = SemacV14.Define.UserType.DefenseCard;//防御卡
                                        break;
                                }
                                switch (mj_lv)
                                {
                                    case "1":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level1;
                                        break;
                                    case "2":
    
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level2;
                                        break;
                                    case "3":
    
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level3;
                                        break;
                                    case "4":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level4;
                                        break;
                                    case "5":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level5;
                                        break;
                                    case "6":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level6;
                                        break;
                                    case "7":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level7
                                            ;
                                        break;
                                    case "8":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level8;
                                        break;
                                    case "9":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level9;
                                        break;
                                    case "10":
                                        re.BypassTimeZoneLevel = SemacV14.Define.BypassTimeZoneLevel.Level10;
                                        break;
                                }
    
                                re.CheckExpire = false;
                                re.ExpiredFrom = System.DateTime.Now;
                                re.ExpiredTo = System.DateTime.Now;
                                re.PersonalPassword = PersonalPassword;
                                re.Group01 = Convert.ToInt32(mj_qz1_id);
                                re.Group02 = Convert.ToInt32(mj_qz2_id);
                                re.Group03 = Convert.ToInt32(mj_qz3_id);
                                re.Group04 = Convert.ToInt32(mj_qz4_id);
                                re.FingerSize = 1;
                                re.OverWrite = true;
                                re.EnabledStatus = true;
                                SemacV14.Service.ExecuteArgz Ea = new SemacV14.Service.ExecuteArgz(ChannelID, re);
                                SemacV14.Service.Actor act = new SemacV14.Service.Actor(Ea);    //实例化Actor
                                //act.OnEntityDataArrival += this.HandleEntity( UserID);//待返回事件处理
                                //act.Send();
    
                                Ea = act.SendAndReceive();           //发送命令,并返回执行结果。
                                //结果判断
                                if (Ea.IsCompleted == true)
                                {
                                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    logfile.WriteFile(str1, Shorttim + ",工号:" + emworkno + "同步到" + terminal_id + "号控制器成功," + Ea.ErrorMessage);
                                    sy.up_mj_p_qz(UserName, kxh, terminal_id, UserID, emcode, mj_qz1, mj_qz2, mj_qz3, mj_qz4, emstate, emlz);
                                }
                                else
                                {
                                    string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    logfile.WriteFile(str1, Shorttim + ",工号:" + emworkno + "同步到" + terminal_id + "号控制器失败," + Ea.ErrorMessage);
                                }
                            }
                        }
                        terminalid_ds.Dispose();
                    }
                    catch (Exception ex)
                    {
                        string Shorttim = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        // string str1 = System.AppDomain.CurrentDomain.BaseDirectory + "/log.txt";
                        logfile.WriteFile(str1, Shorttim + "位置:自动同步人员" + ex.ToString());
                    }
                    System.Threading.Thread.Sleep(5);
                }
                checksyn = true;
                personals_ds.Dispose();
                syn_time = DateTime.Now.ToString("hh:mm:ss ms");
                logfile.WriteFile(str1, "自动同步结束" + syn_time);
                //}
            }
        }
    }
    
    


    pinkbull

    2013年11月19日 16:32