Threading and SqlFileStream. The process cannot access the file specified because it has been opened in another transaction Threading and SqlFileStream. The process cannot access the file specified because it has been opened in another transaction multithreading multithreading

Threading and SqlFileStream. The process cannot access the file specified because it has been opened in another transaction


The transaction does not flow in to the Parallel.ForEach, you must manually bring the transaction in.

//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();}

I also switched from List<ExtractedContent> to ConcurrentQueue<ExtractedContent> because you are not allowed call .Add( on a list from multiple threads at the same time.