开发者

Threading + Unit Test + SqlConnection calls is not working. It works fine not using threading

The main idea is I want to call out to 4 different databases at the same time instead of one at a time. So I am using threading and when it attempts to open the sql connection I get:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Any ideas ? (this is run from a VS unit test if that has anything to do with it)

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
            {
                strin开发者_如何学运维g 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();
        }
    }
}


Ensure you're waiting for the threads to terminate in your unit test. If you spawn off a bunch of threads and let the main thread terminate, the MSTest process will end taking all of your spawned threads with it. You'll often end up with weird exceptions in that case.

The easiest thing to do would be to call Thread.Join() on all the threads you create.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜