This is a fire and forget task from within an existing WebAPI service. The code below simply sends a log event (might be that a client has connected to the service to perform some task) to another service and if it fails should not return an error to the client.
I simply want the exception logged and forgotten about, meanwhile the service will continue to carrying out the original task.
I've used ContinueWith
and am wondering if this is the correct way to do it.
Task.Factory.StartNew(() =>
{
var client = (HttpWebRequest) WebRequest.Create(_url);
client.Method = "POST";
client.ContentType = "application/json";
var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(log));
var requestStream = client.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
var response = client.GetResponse();
requestStream.Close();
response.Close();
}).ContinueWith((ca) =>
{
if (ca.Exception != null)
{
_logger.LogException(LogLevel.Error, ca.Exception.Message, ca.Exception);
}
}, TaskContinuationOptions.OnlyOnFaulted);