I am moving my existing worker role logic to a Stateless Service. There is a method which creates the Timer functionality using Thread.Sleep(). When this method is called from the RunAsync method of the Stateless Service, it throws a warning.
protected override Task RunAsync(CancellationToken cancellationToken)
{
_backgroundService.Start();
if (cancellationToken.IsCancellationRequested)
{
_backgroundService.Stop();
cancellationToken.ThrowIfCancellationRequested();
}
return Task.FromResult(true);
}
The timer method is as follows.
public void Start()
{
_isStopping = false;
while (!_isStopping)
{
try
{
ExecuteRepetitiveTask();
Thread.Sleep(repeatDelaySeconds);
}
catch (Exception e)
{
Thread.Sleep(1000);
}
}
_isStopping = false;
_hasStopped = true;
}
Is this correct, or else do I need to convert this into an asynchronous method?
This is because RunAsync currently expects your override to perform Task-returning asynchronous work. If you run purely synchronous code, like Thread.Sleep, it will block the underlying state machine from completing a role change or open of your service replica/instance, which is bad and that's why you see the warning. We are fixing this in an upcoming release so that it "just works" regardless of whether or not your code is asynchronous, but for the time being, simply wrap your synchronous work in a Task.Run().