I\'m trying to use the new async/await feature to asynchronously work with a DB. As some of the requests can be lengthy, I want to be able to cancel them. The issue I\'m run
Yep, you have to keep you transactionscope on a single thread. Since you are creating the transactionscope before the async action, and use it in the async action, the transactionscope is not used in a single thread. The TransactionScope was not designed to be used like that.
A simple solution I think would be to move the creation of the TransactionScope object and the Connection object into the async action.
UPDATE
Since the async action is inside the SqlConnection object, we cannot alter that. What we can do, is enlist the connection in the transaction scope. I would create the connection object in an async fashion, and then create the transaction scope, and enlist the transaction.
SqlConnection connection = null;
// TODO: Get the connection object in an async fashion
using (var scope = new TransactionScope()) {
connection.EnlistTransaction(Transaction.Current);
// ...
// Do something with the connection/transaction.
// Do not use async since the transactionscope cannot be used/disposed outside the
// thread where it was created.
// ...
}