✅ Async writing and reading from file
Hi! I am creating some kind of storage using streamwriter/streamreader with CSVHelper that will be accessed from different threads. I am thinking about what is the best solution: have some lock variable, use filesharing in FileStream or my plan have no sense and there is other, faster and better way to do this. And are there any possible exception with filesharing?
18 Replies
Have you checked ReaderWriterLock class? https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?redirectedfrom=MSDN
ReaderWriterLock Class (System.Threading)
Defines a lock that supports single writers and multiple readers.
I will check
And second question, are there any possible exception with filesharing?
But if Im right, it's not good for async code like for instance SemaphoreSlim
its thread-affine
Any ideas?
https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=net-7.0 this one is recommended for newer development
ReaderWriterLockSlim Class (System.Threading)
Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.
Thank you so much
Do you know anything about my second question?
No not really, sorry
No problem
I will wait for answer and try to find it by myself
my question is why are there multiple threads and also await/async
What do you mean?
A oh
But I am talking async, not multithreading
wait, you said in the first message
CSVHelper that will be accessed from different threadsright?
isnt async task after await continuing on different thread?
Or I am wrong
we can assume all async/await would be on the same thread (potentially it's not, but usually it is)
But for example loop in task.run won't be on the same thread
asp.net
depends on how you use task.run, for example if it's a LongRunning task (since the task is at a higher level than a thread)
my guess is it probably won't
This is from dotnet docs "f the work you have is CPU-bound and you care about responsiveness, use async and await, but spawn off the work on another thread with Task.Run. If the work is appropriate for concurrency and parallelism, also consider using the Task Parallel Library."
"spawn off the work on another thread with Task.Run"
.
let's put it in this way: would using Task.Run make your program a multithreaded one? yes
does it mean the code will always run on different threads? no, that's the difference with
new Thread()
FileStream is not marked as thread safe, if that's your questionThis is what I am trying to say...
And I don't think I missed the point with "different threads"
Thanks
anyway you can try it yourself, if you just make an async method with an await inside and print the current thread id before the await and after (for example, or it could be a little more complex)
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.