samedi 26 février 2022

Best approach to manage TextWrite Object and multiple Async threads writing to the same file

Use Case

I am writing multi-threaded application where I create multiple Async threads sending Async Http Client Calls and every thread will write its response to a single shared file that the main thread creates before it fires the multiple async threads. I could resolve the thread safety by using TextWriter.Synchronized but this will require me to pass the same object to all the threads as a parameter, I can't do as this will break my design as the interface method my domain object implementing does not have such a parameter accepting TextWriter object, to resolve this issue I added a method to my ObjectFactory Class that returns a synchronized TextWriter Object, the problem with this approach is that multiple objects will try to access the same file and they will fail eventually with FileInUse Error and I do not like the idea of having multiple objects for the same purpose.

Question

I am thinking of Object Pooling Design Pattern to solve this issue. It is the first time I am implementing this approach which from what I read it is mainly used to minimize the cost of the creation of the complex objects multiple time but here I am using it to maintain the singularity of the object during the life time of the main thread which I am not sure it is correct.

Aucun commentaire:

Enregistrer un commentaire