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)
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