SQL Exception: "Impersonate Session Security Context" cannot be called in this batch because a simul

Posted by kasey on Stack Overflow See other posts from Stack Overflow or by kasey
Published on 2010-03-30T13:24:30Z Indexed on 2010/04/08 8:03 UTC
Read the original article Hit count: 575

When opening a connection to SQL Server 2005 from our web app, we occasionally see this error:

"Impersonate Session Security Context" cannot be called in this batch because a simultaneous batch has called it.

We use MARS and connection pooling.

The exception originates from the following piece of code:

protected SqlConnection Open()
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = m_ConnectionString;
    if (connection != null)
    {
        try
        {
            connection.Open();
            if (m_ExecuteAsUserName != null)
            {
                string sql = Format("EXECUTE AS LOGIN = {0};", m_ExecuteAsUserName);
                ExecuteCommand(connection, sql);
            }
        }
        catch (Exception exception)
        {
            connection.Close();
            connection = null;
        }
    }
    return connection;
}

I found an MS Connect article which suggests that the error is caused when a previous command has not yet terminated before the EXECUTE AS LOGIN command is sent. Yet how can this be if the connection has only just been opened?

Could this be something to do with connection pooling interacting strangely with MARS?

UPDATE: For the short-term we have implemented a workaround by clearing out the connection pool whenever this happens, to get rid of the bad connection, as it otherwise keeps getting handed back to various users. (Not too bad as this only happens a couple of times a day.) But if anyone has any further ideas, we are still looking out for a real solution...

© Stack Overflow or respective owner

Related posts about sql-server-2005

Related posts about ASP.NET