0

I have an async write but I want to make sure if the method is called again while a write is still underway, it waits until the file is ready before trying the next attempt.

I want this all to be non blocking.

Is this the correct way to do it?

Do i even need the lock? Or does the streamwriter already look after this.

lock (fileWriterLock) { FileWriteAsync(filename, data); } 

and then..

 public async Task FileWriteAsync(string filePath, string messaage) { using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) using (StreamWriter sw = new StreamWriter(stream)) { await sw.WriteLineAsync(messaage); } } 
7
  • If there’s a lock it can’t really be non-blocking. Can it really be called from multiple threads at the same time? Commented Aug 22, 2020 at 11:51
  • No Its only in one thread. I just want to write to the file in a way that doesn't stop executing of code, and doesn't affect speed/execution of the main thread. Commented Aug 22, 2020 at 11:53
  • If it’s in one thread you don’t need a lock at all. But if you want to write in the background then you’d need another thread, async doesn’t mean it will run concurrently and fire-and-forget isn’t a great idea often Commented Aug 22, 2020 at 11:54
  • That's correct I want to run it in another thread. Looks like my code is wrong. Commented Aug 22, 2020 at 11:57
  • Your question is overly broad. However, your requirement that the synchronization be non-blocking seems to be the crux of the matter. See duplicate for approaches to handling synchronization without blocking. Note that while the FileShare value passed to the FileStream constructor will prevent concurrent access to the file, it doesn't cause any sort of wait/synchronization; another thread or process trying to open the file will just fail. ... Commented Aug 22, 2020 at 16:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.