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
In your code there is no need to using async/await, just set up a new thread to perform long 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);
}
}
Using Task.Factory.StartNew(SendAliveMessage, TaskCreationOptions.LongRunning)
to perform the operation.
If you really want to using async/await pattern, just call it in constructor without await modifier and the forget it.
public Client()
{
_webRequest = WebRequest.Create("some url");
_webRequest.Method = "POST";
IsRunning = true;
SendAliveMessageAsync(); //just call it and forget it.
}
I think it's not good idea to set up a long running thread or using async/await pattern. Timers maybe more suitable in this situation.