I\'m new to C#s await/async and currently playing around a bit.
In my scenario I have a simple client-object which has a WebRequest
Since it is a fire and forget operation, you should start it using
SendAliveMessageAsync();
Note that await does not start a new Task. It is just syntactical sugar to wait for a Task to complete.
A new thread is started using Task.Run.
So inside SendAliveMessageAsync you should start a new Task:
private async Task SendAliveMessageAsync()
{
const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
await Task.Run( () => {
var seconds = 0;
while (IsRunning)
{
if (seconds % 10 == 0)
{
await new StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage);
}
await Task.Delay(1000);
seconds++;
}
});
}