EF4, TransactionScope and Task <>

Is it possible to open TransactionScope , start the async Task download, which works with the EF4 ObjectContext , and then commit the result?

How is the current transaction scope displayed in EF4? Could it be if / when the task is assigned to another thread in the transaction area?

+4
source share
2 answers

Yes it is. Firstly, the Entity Framework simply uses the provider at the bottom (System.Data.SqlClient by default), which selects the context of the "ambient" transaction from the executable stream. So from there, the only trick applies to one transaction on the Tasks that you rotate. I explained how you can do this here in this post .

While this post was more about creating PLINQ jobs, the same approach applies if you manually deploy your own Tasks . If you need sample code, please give me basic information on how your spawning Task will work, so that I can give a good code example.

+4
source

No, you cannot (usefully) do this.

Although Drew Marsh's answer is correct (that there are ways to make boundaries of overlapping transactions), it will not help you. ObjectContext not thread safe - you should not access it from other threads, and you definitely do not need to update it in other threads; you will have undefined behavior: you are likely to encounter data corruption that (if you're lucky) will cause crashes.

If you need access to multiple streams of ObjectContext , you need to manually serialize the access, for example, using locks. But if you do, you can simply access the context from a single thread; it is usually simpler and almost always faster - and then you will not have problems with your transactions.

If you insist on manually synchronizing access to the ObjectContext , rather than using a stream, you can also use a simple CommittableTransaction and pass it on by understanding, rather than using an external transaction; since you will need to manually manage the transaction, since it is clearer to do this with an explicit object descriptor, rather than complex state transitions (where accurate information about which thread is running, which is vital, but not explicit in the code).

By the way, if you use an external transaction, I will be careful with scheduling tasks, especially with the C # 5 asynchronous function, as you may need to know clearly when the execution can change the thread (I never tried this, so I can not give you any pointers, unfortunately).

Summary: just do not do this: you do not type concurrency multithreading due to ObjectContext limitations (and in practice, the database), so you can also leave one transaction on one thread and save it simply. Future companions will be grateful for the clarity.

0
source

Source: https://habr.com/ru/post/1385571/


All Articles