线程+单元测试+ SqlConnection调用无效。它工作正常,不使用线程

时间:2011-08-08 17:08:58

标签: c# multithreading unit-testing sqlconnection

主要想法是我想同时呼叫4个不同的数据库,而不是一次呼叫。所以我使用线程,当它尝试打开sql连接时,我得到:

  

无法评估表达式,因为代码已优化或a   本机框架位于调用堆栈之上

有什么想法吗? (这是从VS单元测试运行的,如果它与它有任何关系)

using System;
using System.Data.SqlClient;
using System.Threading;
using Manual101.BLLDAL;

namespace Manual101.BLL
{
    public class AgencySender
    {
        private CourtCase localcc;
        private string connectionString = xxx; 
        public AgencySender(CourtCase cc)
        {
            this.localcc = cc;
        }

        public void SendOAG()
        {
            try
            {
                string queryString = "select JustisId from ReviewFilingCallbackMessage";

                using (SqlConnection connection =
                       new SqlConnection(connectionString))
                {
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = queryString;

                    connection.Open();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                var x = reader["JustisId"].ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // log errors
            }
        }
    }

    public class AgencySenderHelper
    {
        private string connectionString = xxx    
        public void SendData(CourtCase cc)
        {
            //  AgencySender ags = new AgencySender(cc);
            //  ags.SendOAG();

            AgencySender ags = new AgencySender(cc);
            Thread thread = new Thread(new ThreadStart(ags.SendOAG));
            thread.Start();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

确保您等待线程在单元测试中终止。如果你产生一堆线程并让主线程终止,那么MSTest进程将结束所有你生成的线程。在这种情况下,你经常会遇到奇怪的例外。

最简单的方法是在你创建的所有线程上调用Thread.Join()。