Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I stop an async method I am waiting for from outside the method

I am using async methods and a SemaphoreSlim object to wait for and detect a click. Eventually, on a different method being called, I want to stop the async method that is being run and continue as if the method completed.

Incase it affects the answer, I am using Windows Forms.

Here is a skeleton of my problem (not my actual code)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private SemaphoreSlim _semaphoreClick = new SemaphoreSlim(0, 1);

static void Main() 
{
    RunProgram();
    SomeFinishedFuncion();
}

async void RunProgram()
{
    object thing = await WaitForSemaphoreSlim();   
}

async Task<object> WaitForSemaphoreSlim() 
{
    object thing;
    // do stuff
    
    await _semaphoreClick.WaitAsync();
        
    // do stuff
    return thing;
}


void OnStopProgram() 
{
    // Do something here that will stop the RunProgram() 
    // which will make Main() continue to SomeFinishedFunction()
}

>Solution :

Use a CancellationTokenSource and CancellationToken:

private SemaphoreSlim _semaphoreClick = new SemaphoreSlim(0, 1);
private CancellationTokenSource cts = new CancellationTokenSource();

static void Main() 
{
    RunProgram(cts.Token);
    SomeFinishedFuncion();
}

async void RunProgram(CancellationToken cToken)
{
    try
    {
        object thing = await WaitForSemaphoreSlim(cToken);
    }
    catch(OperationCanceledException)
    {
         //When a token is cancelled this exception is raised.
    }   
}

async Task<object> WaitForSemaphoreSlim(CancellationToken cToken) 
{
    object thing;
    // do stuff
    
    await _semaphoreClick.WaitAsync(cToken);
        
    // do stuff
    return thing;
}


void OnStopProgram() 
{
    cts.Cancel();
}

Side note: be careful using async void: Avoid Async Void

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading