Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TaskLocal<T> Class?

We are looking to add TPL to a particular portion of our processes that are long-running and can be split into concurrent sub-processes. The core issue that we are running into at this point is that our current code is dependent on an EntityFramework 6.1 DbContext which is not thread-safe. I have spent some time digging into TPL and its innerworkings. It doesn't appear that we can use ThreadLocal, as a Task can/will have multiple threads running on it throughout its lifetime (if I understand correctly) and the executing task will ultimately be interacting with multiple ThreadLocal instances.

The next thought I had around this is a TaskLocal object that could store the DbContext throughout the lifetime of the task (thereby cleanly separating it from other concurrent Tasks that are running this same code -- each with their own corresponding TaskLocal).

There is mention of something like this in this thread but it does not offer any code or link to code.

Is this possible? And also, is my understanding of TPL thus far correct?

like image 971
Mike-E Avatar asked Jun 30 '26 21:06

Mike-E


1 Answers

Actually, .NET already has one: AsyncLocal<T> class.
Looks like this is what you want.

like image 56
Dennis Avatar answered Jul 02 '26 11:07

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!