简体   繁体   中英

Sharing a db connection between threads in a C# application?

我发现关于这个主题的信息非常少,希望有人可以指导我一些信息和可能的示例代码。

Generally connections are not thread safe(SqlConnection ,MySqlConnection and OracleConnection specifically mention that they are not thread safe).

Don't share a connection between threads.

我会说不要共享连接对象本身,只需创建一个新连接,让ADO.net处理连接池。

To respond to the actual parameters of the question, rather than dismissing them, I would wrap the DbCommand to help synchronize access to the connection ( if and only if you absolutely have to).

public class SyncedDbCommand : DbCommand
{
    private DbCommand _cmd;
    private object _sync;

    public SyncedDbCommand(DbCommand cmd, object sync)
    {
        _cmd = cmd;
        _sync = sync;
    }

    // omitted basic proxy method overrides

    protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
    {
        Monitor.Enter(_sync);
        return _cmd.ExecuteReader();
    }

    public override int ExecuteNonQuery()
    {
        Monitor.Enter(_sync);
        return _cmd.ExecuteNonQuery();
    }

    public override object ExecuteScalar()
    {
        Monitor.Enter(_sync);
        return _cmd.ExecuteScalar();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            Monitor.Exit(_sync);
        }
        base.Dispose(disposing);
    }
}

To use the sample, you have to instantiate it with an actual DbCommand as well as some object instance that is shared across all usages of a connection. In the simplest use, you could even pass the connection object itself as the lock object. The instantiation should occur in a using statement. This does not absolve you from knowing exactly what your usage requirements are and how the Monitor class and locking work.

One way or another, you want to synchronize usage of the connection across threads, and the above is one approach to doing so.

野外没有示例代码,因为(几乎)没有人这样做,因为它是一个非常非常糟糕的主意。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM