Skip to content

Starting multiple transactions in separate threads causes unexpected behavior #1758

Closed

Description

@Charles-Gagnon

Describe the bug

If multiple transactions are started in separate threads, but using the same connection, then you can end up with multiple transaction objects. This is unexpected since normally if you try to begin multiple transactions on the same connection it throws an InvalidOperationException.

To reproduce

This results in no errors being produced and both tables being created.

    var conn = new SqlConnection(...);
    var task1 = Task.Run(() =>
    {
        return conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
    });
    var task2 = Task.Run(() =>
    {
        return conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
    });

    SqlTransaction t1 = await task1;
    SqlTransaction t2 = await task2;
    using (SqlCommand cmd1 = new SqlCommand("CREATE TABLE t1 (c1 int)", conn, t1))
    {
        cmd1.ExecuteNonQuery();
    }

    using (SqlCommand cmd2 = new SqlCommand("CREATE TABLE t2 (c1 int)", conn, t2))
    {
        cmd2.ExecuteNonQuery();
    }

    t1.Commit();
    t2.Commit();

If I await the first task though before starting the second then it errors as expected

    var conn = new SqlConnection(...);
    var task1 = Task.Run(() =>
    {
        return conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
    });
    SqlTransaction t1 = await task1;
    var task2 = Task.Run(() =>
    {
        return conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead); // This now throws
    });

    SqlTransaction t2 = await task2;
    using (SqlCommand cmd1 = new SqlCommand("CREATE TABLE t1 (c1 int)", conn, t1))
    {
        cmd1.ExecuteNonQuery();
    }

    using (SqlCommand cmd2 = new SqlCommand("CREATE TABLE t2 (c1 int)", conn, t2))
    {
        cmd2.ExecuteNonQuery();
    }

    t1.Commit();
    t2.Commit();

Expected behavior

I would expect this to throw an exception, like what happens if you try to begin two transactions on the same thread :

    var t1 = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
    var t2 = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead); // This throws

Further technical details

Microsoft.Data.SqlClient version: 5.0.0
.NET target: .NET 6
SQL Server version: 2022
Operating system: Windows 11 Enterprise

Additional context

An interesting thing I noticed was that the TransactionId of the internal transaction object is 0 for the second transaction object :

image

There's also some interesting behavior where it seems like the transactions are linked somehow, none of the transactions are committed until both of the SqlTransaction objects have Commit called. Calling it on just one results in nothing happening (although I haven't dug into the SQL server side to see what all is happening there yet - just verified that the table isn't created)

Activity

  1. Wraith2 commented on Sep 11, 2022

    @Wraith2
    Contributor

    What you're doing is not supported. Connections are not safe for multithreaded access, almost nothing in this library is. If you want to pass a connection or other linked object around between threads that's usually safe because there is no thread affinity but you should not access the same object a thread while another thread may be trying to use it.

  2. JRahnama commented on Sep 12, 2022

    @JRahnama
    Contributor

    @Charles-Gagnon as @Wraith2 mentioned Connections are not thread safe and the action is not supported.

  3. Charles-Gagnon commented on Sep 12, 2022

    @Charles-Gagnon
    Author

    Thanks. Is this documented anywhere? I looked around a bit and didn't see anything specific - it seems like a good idea to call that out (especially with async becoming such a common thing for even simple apps now).

  4. Wraith2 commented on Sep 12, 2022

    @Wraith2
    Contributor

    As far as I remember the policy on thread safety is to document where methods are thread safe and anything that does not mention it is not safe. So assume nothing is safe unless you are explicitly told that it is.

    Async methods and the code that results from compiling them still executes serially even though it can move between threads. As i mentioned above as long as only one thread is interacting with the objects then you're usually quite safe. What your example does is cause multiple threads to use the same command object through your use of Task.Run (explicitly for creating long running tasks) and that's not safe.

  5. JRahnama commented on Sep 13, 2022

    @JRahnama
    Contributor

    @Wraith2 thanks for extensive response.

    I am closing the issue as it is by design and there is nothing to be done from our side.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions