How to create an async method that can only execute from one thread at a time?

Viewed 52

I have a IO.Stream which I need to write and then read from. Since the response is directly tied to the data sent, I need to keep this method from executing in parallel, so that the integrity of this is guaranteed. Now, I also want this method to be awaitable, is that even possible ? I wrapped the stream into a synchronized steam, which will prevent interference during reads and writes, but it will not guarantee that the correct order of write and read operations is kept. I'm kinda lost on how to implement this, since I can not lock the stream if I want to use the async await approach.

2 Answers

You can use SemaphoreSlim.WaitAsync.

    static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
    //Asynchronously wait to enter the Semaphore. If no-one has been granted access to the Semaphore, code execution will proceed, otherwise this thread waits here until the semaphore is released
    await semaphoreSlim.WaitAsync();
    try
    {
        await Task.Delay(1000);
    }
    finally
    {
        semaphoreSlim.Release();
    }

Thanks for your answers, I found a different solution. I am enqueueing the send commands and matching them to the responses which are read in a separate thread now. Since the writes and reads are serial, they can be securely matched by order.

Related