So I've ASP .NET application that exposes two endpoints. One for starting a continuous Task and other to time it out
My controller looks something like this
public class SomeController: ControllerBase
{
private readonly ISomeService _service;
public SomeController(ISomeService service)
{
_service= service;
}
[HttpPost, Route("service/stop")]
public ActionResult StopService()
{
_service.StopService();
return Ok();
}
[HttpPost, Route("service/start")]
public async Task<ActionResult> StartService()
{
int result = await _service.Start();
return Ok(new {Result = result});
}
}
and the service looks like
public class SomeService : ISomeService
{
private static TaskCompletionSource<bool> tcs;
private readonly IInternalService _internalService;
public SomeService(IInternalService internalService) => _internalService = internalService;
public void StopService()
{
tcs.TrySetException(new TimeoutException("Operation timed out") );
}
public Task<int> StartService()
{
tcs = new TaskCompletionSource<bool>();
EventHandler<EventArguments> eventHandler = (sender, e) => EventHandler(sender, e, parameter1, parameter2);
try
{
_internalService.Event += eventHandler;
while (!(eventResult = (await tcs.Task))) ;
}
catch (Exception ex)
{
_logger.LogError($"Event failed because of {ex.Message}");
throw;
}
finally
{
_internalService.Event -= eventHandler;
}
}
private void EventHandler(object sender, EventArguments e, string parameter1, bool parameter2)
{
if (some condition)
{
tcs.TrySetException(new Exception("Event handling failed because condition was not met");
return;
}
try
{
_internalService.SomeOperation(parameter2);
tcs.SetResult(true);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
return;
}
}
}
When the event handler inner exceptions set the tasks completion source to status faulted with exception everything works fine. But when I start the service and after a while set the timeout exception with StopService API call the exception gets caught in StartService try...catch but then the API automatically triggers another call to StartService method.