14

我正在提取 SQL 文件表中文件的内容。如果我不使用 Parallel,则以下代码有效。

同时读取 sql 文件流(并行)时,出现以下异常。

进程无法访问指定的文件,因为它已在另一个事务中打开。

TL;博士:

从 Parallel.ForEach 中的 FileTable(使用 GET_FILESTREAM_TRANSACTION_CONTEXT)读取文件时,出现上述异常。

示例代码供您试用:

https://gist.github.com/NerdPad/6d9b399f2f5f5e5c6519

更长的版本:

获取附件并提取内容:

var documents = new List<ExtractedContent>();
using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    var attachments = await dao.GetAttachmentsAsync();

    // Extract the content simultaneously
    // documents = attachments.ToDbDocuments().ToList(); // This works
    Parallel.ForEach(attachments, a => documents.Add(a.ToDbDocument())); // this doesn't

    ts.Complete();
}

DAO 读取文件表:

public async Task<IEnumerable<SearchAttachment>> GetAttachmentsAsync()
{
    try
    {
        var commandStr = "....";

        IEnumerable<SearchAttachment> attachments = null;
        using (var connection = new SqlConnection(this.DatabaseContext.Database.Connection.ConnectionString))
        using (var command = new SqlCommand(commandStr, connection))
        {
            connection.Open();

            using (var reader = await command.ExecuteReaderAsync())
            {
                attachments = reader.ToSearchAttachments().ToList();
            }
        }

        return attachments;
    }
    catch (System.Exception)
    {
        throw;
    }
}

为每个文件创建对象:该对象包含对 GET_FILESTREAM_TRANSACTION_CONTEXT 的引用

public static IEnumerable<SearchAttachment> ToSearchAttachments(this SqlDataReader reader)
{
    if (!reader.HasRows)
    {
        yield break;
    }

    // Convert each row to SearchAttachment
    while (reader.Read())
    {
        yield return new SearchAttachment
        {
            ...
            ...
            UNCPath = reader.To<string>(Constants.UNCPath),
            ContentStream = reader.To<byte[]>(Constants.Stream) // GET_FILESTREAM_TRANSACTION_CONTEXT() 
            ...
            ...
        };
    }
}

使用 SqlFileStream 读取文件: 此处抛出异常

public static ExtractedContent ToDbDocument(this SearchAttachment attachment)
{
    // Read the file
    // Exception is thrown here
    using (var stream = new SqlFileStream(attachment.UNCPath, attachment.ContentStream, FileAccess.Read, FileOptions.SequentialScan, 4096))
    {
        ...
        // extract content from the file
    }

    ....
}

更新1:

根据这篇文章,这似乎是一个隔离级别的问题。有没有人遇到过类似的问题?

4

1 回答 1

4

交易不流入Parallel.ForEach,您必须手动将交易带入。

//Switched to a thread safe collection.
var documents = new ConcurrentQueue<ExtractedContent>();
using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    var attachments = await dao.GetAttachmentsAsync();
    //Grab a reference to the current transaction.
    var transaction = Transaction.Current;
    Parallel.ForEach(attachments, a =>
    {
        //Spawn a dependant clone of the transaction
        using (var depTs = transaction.DependentClone(DependentCloneOption.RollbackIfNotComplete))
        {
            documents.Enqueue(a.ToDbDocument());
            depTs.Complete();
        }
    });

    ts.Complete();
}

我也从 切换到List<ExtractedContent>ConcurrentQueue<ExtractedContent>因为不允许您同时.Add(从多个线程调用列表。

于 2015-05-11T22:05:05.230 回答