如何清洁使用现有连接或创建/处置新连接?

时间:2018-09-08 15:56:13

标签: c# refactoring

在某些情况下,有时我想在同一连接中执行代码(以使用临时表等),但是大多数时候我想尽快打开和关闭连接。

public int BulkInsert<T>(IDataReader dataReader, Dictionary<string, string> columnMappings = null, int timeoutInSeconds = 120)
{
    if (_sqlConnection != null)
    {
        return BulkInsert<T>(dataReader, _sqlConnection, columnMappings, timeoutInSeconds);
    }

    using (var tempConnection = new SqlConnection(_connectionString))
    {
        return BulkInsert<T>(dataReader, tempConnection, columnMappings, timeoutInSeconds);
    }
}

如何使这段代码更简洁,而不是两个单独的调用?

我的尝试

public int BulkInsert<T>(IDataReader dataReader, Dictionary<string, string> columnMappings = null, int timeoutInSeconds = 120)
{
    var rv = 0;
    var conn = _sqlConnection ?? new SqlConnection(_connectionString);
    try {
        rv = BulkInsert<T>(dataReader, conn, columnMappings, timeoutInSeconds);
    } finally {
        if (conn != _sqlConnection)
        {
            conn.Dispose();
        }
    }

    return rv;
}

但是我对此并不满意。

P.S。我不确定这是属于stackoverflow还是编程,但是我发现是因为using的使用是c#特有的,并且不仅仅是基于样式的意见,而是重构。

2 个答案:

答案 0 :(得分:0)

我建议使用以下模式

* {
  padding: 0;
  margin: 0;
}

@media print {
  .item {
    page-break-inside: avoid;
  }
}

.item {
  padding: 0.25in;
  line-height: 0.35in;
}

.row {
  display: flex;
  justify-content: space-between;
}

.label {
  text-align: center
}

.text1 {
  text-align: left;
}

.text2 {
  text-align: right;
}

.separator {
  margin-left: 1pt;
  margin-right: 1pt;
  vertical-align: bottom;
  flex-grow: 1;
  height: 1.5em;
  border-bottom: 1px dotted black;
  /* These last two rules are likely superfluous */
  -webkit-print-color-adjust: exact !important;
  color-adjust: exact !important;
}

很明显,您正在尝试实现什么,并且没有分支。您可以将SqlConnection和bool封装到一个简单的结构中,以方便切出OUT参数。

这里的一个不错的选择是该函数不知道或不在乎其连接来自何处,无论它是缓存的还是来自另一个调用的持久性,并且允许简单的多线程处理(确保连接可以租借持久性连接或如果永久连接已在使用中,请根据需要创建一个新的连接。

答案 1 :(得分:0)

哦,我发现这种方法基于C# conditional using block statement

private void myFunc()
{
    // The ensureConnection method does the null check and creates a connection
    bool connectionEstablished;
    SqlConnection connection = ensureConnection(out connectionEstablished);
    try
    {
       // Do some work with the connection.

    }
    finally
    {
       // If the connection was established for this call only, the disposeConnection
       // function carries out disposal (or caching etc).
       disposeConnection(connection, connectionEstablished);
    }
}