Raskolnikov
Raskolnikov

Reputation: 4009

To many threads waiting on semaphore

Let assume that I have timer calling method every second.

Method is async (must be async) and I sync method by using SemaphoreSlim. Method require 5 seconds to finish.

I will have many threads waiting on semaphore. Is this true? Is that a problem ? Since this is timer I will have more and more threads waiting on semaphore.

How can I resolve this issue ? Is it possible to not wait if semaphore is not released (just skip code)?

Timer:

  PoolReportTimer = new Timer(ReportTimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));

Method:

    private static SemaphoreSlim semaphoreSlimValue = new SemaphoreSlim(1, 1);

    private async void ReportTimerCallback(object state)
    {
        try
        {
            await semaphoreSlimValue.WaitAsync();
            await Task.FromResult(0);
            Thread.Sleep(5000);
        }
        finally
        {
            semaphoreSlim.Release();
        }
    }

EDIT:

I want to get report every few second in async method. But I want be sure that this will not be problem if method need to much time to finish.


EDIT 2 - Solution:

       private async void ReportTimerCallback(object state)
        {
            if (await semaphoreSlimValue.WaitAsync(10))
            {
                try
                {
                    await Task.FromResult(0);
                    Thread.Sleep(5000);
                }
                finally
                {
                    semaphoreSlim.Release();
                }
            }
        }

Upvotes: 0

Views: 1843

Answers (1)

nvoigt
nvoigt

Reputation: 77364

If you want to skip waiting for the semaphore if another thread has a hold on it, you can use the WaitAsync(TimeSpan) method, to pass a timespan (let's say a tenth of a second) and await the result. If it's false, somebody else is still holding your resource and you can react to that fact (for example by skipping whatever you wanted to do).

Upvotes: 2

Related Questions