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
property. The client should send periodically alive-messages over the WebRequest
s RequestStream
.
This is the constructor of the client-object:
public Client()
{
_webRequest = WebRequest.Create("some url");
_webRequest.Method = "POST";
IsRunning = true;
// --> how to start the 'async' method (see below)
}
and the async alive-sender method
private async void SendAliveMessageAsync()
{
const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
var seconds = 0;
while (IsRunning)
{
if (seconds % 10 == 0)
{
await new StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage);
}
await Task.Delay(1000);
seconds++;
}
}
How should the method be started?
new Thread(SendAliveMessageAsync).Start();
or
Task.Run(SendAliveMessageAsync); // changing the returning type to Task
or
await SendAliveMessageAsync(); // fails as of the constructor is not async
My question is more about my personal understanding of await/async
which I guess may be wrong in some points.
The third option is throwing
The 'await' operator can only be used in a method or lambda marked with the 'async' modifier
Thread
that send alive messages. – Frijolawait
is pointless as you're not really interested in waiting for it to complete. I would simply use the thread approach then. Personally I consider tasks as smaller contained units of work that needs to be run asynchronously. – Bluetonguenew StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage)
- await or otherwise - asStreamWriter
isIDisposable
and must be properly disposed of once used. This syntax doesn't allow you to call.Dipose()
. – SteradianStreamWriter
is also initialized in the constructor but for simplicity reasons not shown here. – Frijol