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);
        }
    }
Dan Pettis
  • 113
  • 5
  • If there’s a lock it can’t really be non-blocking. Can it really be called from multiple threads at the same time? – Sami Kuhmonen Aug 22 '20 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. – Dan Pettis Aug 22 '20 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 – Sami Kuhmonen Aug 22 '20 at 11:54
  • That's correct I want to run it in another thread. Looks like my code is wrong. – Dan Pettis Aug 22 '20 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. ... – Peter Duniho Aug 22 '20 at 16:47
  • ... The `lock` statement can synchronize within the process, but a) will block the thread trying to take the lock if the lock is already held, and b) doesn't work across processes. The `Mutex` class solves the second problem, but not the first. You may find information in https://stackoverflow.com/questions/23153155/named-mutex-with-await useful here. – Peter Duniho Aug 22 '20 at 16:47
  • [`SemaphoreSlim`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.8). Dup reference doesn't contain the semaphore usage but it's the simpliest way to make an `async` lock. – aepot Aug 22 '20 at 17:34

0 Answers0