当 SqlDataReader returns 记录太多时创建新的 SqlFileStream 对象时出错

Getting error creating new SqlFileStream object when SqlDataReader returns too many records

我正在尝试访问 SqlServer FILESTREAM table 中的多个文件。当 SqlDataReader 返回的文件数量相对较少时,此代码有效。大约 20 个文件。但是,当 SqlDataReader 返回几百条记录时,我在第一次通过 while 循环时收到此错误:"The process cannot access the file specified because it has been opened in another transaction."

错误发生在这一行:

sfsList.Add(fileNameText, new SqlFileStream(filePath, txContext, FileAccess.Read));

有什么想法吗?

代码段如下:

        int ProjectID;
        int.TryParse(Request.QueryString["ProjectID"], out ProjectID);
        string filePath = null;
        byte[] txContext = null;
        string fileNameText = null;
        Dictionary<string, SqlFileStream> sfsList = new Dictionary<string, SqlFileStream>();

        using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ATRD"].ToString()))
        {
            cn.Open();
            using (SqlTransaction trn = cn.BeginTransaction("GetAllDocsTran"))
            {
                SqlCommand cmd = new SqlCommand("GetAllDocs", cn, trn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ProjectID", ProjectID);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    try
                    {
                        while (reader.Read())
                        {
                            txContext = (reader["txContext"] as byte[]);
                            filePath = reader["filePath"].ToString();
                            fileNameText = reader["fileNameText"].ToString();
                            sfsList.Add(fileNameText, new SqlFileStream(filePath, txContext, FileAccess.Read));

                        }
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                        try
                        {
                            cmd.Transaction.Rollback();
                        }
                        catch (Exception ex2)
                        {
                            Response.Write(ex.Message + ex2.Message);
                        }
                    }
                }
            }
        }

我通过首先选择我想要的文件的所有主键并将它们添加到集合中来解决这个问题。然后我就干脆用一个循环把文件一个一个的取出来了