Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c# - How to Improve Semaphore in Recursive Method?

I created a method which is using semaphore and after getting response if this is not what I wanted I am calling same method. Here is code

  public async Task SampleFunction()
        {
        bool responseStatus;
            SemaphoreSlim semaphore = null;
            try
            {
                semaphore = await Task.Run(async () =>
                {
                    OtherLockSemaphore.Wait();
                    try
                    {
                        SemaphoreSlim semThread = new SemaphoreSlim(1);
                        
                        semThread.Wait();

                        try
                        {
                            // Call other method here which set vale of responseStatus True/False
                            responseStatus = await someOterFunctionCallAsync();
                            return semThread;
                        }
                        catch
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        OtherLockSemaphore.Release();
                    }
                }).ConfigureAwait(false);

                await semaphore.WaitAsync().ConfigureAwait(false);
                
                // Check if responseStatus is false we need to call again
                if (!responseStatus)
                {
                    await SampleFunction().ConfigureAwait(false);
                }
            }
            finally
            {
                semaphore.Release();
            }
        }

I am not sure if this is correct way to do so looking for suggestion. As you can see I am using await SampleFunction().ConfigureAwait(false); inside this function to call it again.

supposer I executes this function

await SampleFunction();

as you can see internally it is calling other method to check status, if that is false then it again call it self. It will do until status returned true.

So I am looking for better solution as it will call function in loop.

question from:https://stackoverflow.com/questions/65932834/how-to-improve-semaphore-in-recursive-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...