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
Here's an option since you can't call await
from inside a constructor.
I would suggest using Microsoft's Reactive Framework (NuGet "Rx-Main").
The code would look like this:
public class Client
{
System.Net.WebRequest _webRequest = null;
IDisposable _subscription = null;
public Client()
{
_webRequest = System.Net.WebRequest.Create("some url");
_webRequest.Method = "POST";
const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
var keepAlives =
from n in Observable.Interval(TimeSpan.FromSeconds(10.0))
from u in Observable.Using(
() => new StreamWriter(_webRequest.GetRequestStream()),
sw => Observable.FromAsync(() => sw.WriteLineAsync(keepAliveMessage)))
select u;
_subscription = keepAlives.Subscribe();
}
}
This code handles all of the threading required and properly disposes of the StreamWriter
as it goes.
Whenever you want to stop the keep alives just call _subscription.Dispose()
.