There is no need to use async / wait in your code, just set up a new thread for continuous operation.
private void SendAliveMessage() { const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}"; var sreamWriter = new StreamWriter(_webRequest.GetRequestStream()); while (IsRunning) { sreamWriter.WriteLine(keepAliveMessage); Thread.Sleep(10 * 1000); } }
Use Task.Factory.StartNew(SendAliveMessage, TaskCreationOptions.LongRunning) to perform the operation.
If you really want to use the async / await pattern, just call it in the constructor without the wait modifier and forget it.
public Client() { _webRequest = WebRequest.Create("some url"); _webRequest.Method = "POST"; IsRunning = true; SendAliveMessageAsync();
I think this is not a good idea - create a long stream or use the async / await template. Timers may be more appropriate in this situation.
source share