1

I have a service which is responsible to do background tasks. every task has some database interactions and must has its own connectionstring to connect to the different database. for handling the situation I create new thread for each task and i have a shared dictionary to store threadid and own connectionstring (when i want to run task I know the connectionstring). my dataaccess layer responsible to handle request from web,mobile,this service etc and a manager to get proper connectionstring (except this service it returns static connectionstring and for this service it gets threadid from CurrentThread so it has connectionstring ) . my requirement is to use Task.Run() instead of New Thread() and use Task.Run() in some methods and use async methods inside related methods so I lose ability to use shared dictionary because every task run and in some cases every async method has their own threadid. I do not have enough time to implement strategy pattern for correct solution. I did some research and test so I figured out CultureInfo property in System.Threading.Thread.CurrentThread.CurrentCulture can be change in parent Task and all sub methods (including the async methods and the methods that use Task.Run) use changed CultureInfo without any change in other thread. so every parent task and its children have their own CultureInfo. I want something with the exact behavior . I tried to Extend CultureInfo but in sub threads I could not access them. I tried to use System.Threading.Thread.CurrentContext.SetProperty the currentcontext was frozen. I tried to use ActionBlock ; it did not work too. does anyone has idea about my problem?

  • Could ConcurrentDictionary be the droid you are looking for? https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=netframework-4.8 – Christopher Aug 03 '19 at 19:39
  • @Christopher imagine I am in a async method, I do not have any clue about my main thread is, so I do not have opportunity to get my related connection string, the object that has related connection string must have flow inside from main to all children without effecting other threads – Alireza Yadegari Aug 04 '19 at 05:42
  • No mater how you do Multitasking, the thing you do MT with will have an ID of some sort. That one can be used as Key for the CuncurrentDictionary. As the key is unique and the Dictionary is concurrent, no issues will occur. – Christopher Aug 04 '19 at 11:06

1 Answers1

1

I think you are after an AsyncLocal. The concept is explained by Stephan Cleary:

https://blog.stephencleary.com/2013/04/implicit-async-context-asynclocal.html

After you have understood the concept this answer should suite your needs: How do the semantics of AsyncLocal differ from the logical call context?

Alois Kraus
  • 13,229
  • 1
  • 38
  • 64