我想在现有的 WebAPI 服务中实现“即发即忘”任务。下面的代码只是将日志事件(可能是客户端已连接到服务以执行某些任务)发送到另一个服务,如果失败,不应向客户端返回错误。
我只是希望记录并忘记异常,同时服务将继续执行原始任务。
我用过
ContinueWith
:
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);
或者,我也认为我可以这样做,即不使用延续。
Task.Factory.StartNew(() =>
{
try
{
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();
}
catch(Exception e)
{
_logger.LogException(LogLevel.Error, e.message, e)
}
})
这些是正确的做法吗?
在
ContinueWith
中执行以下操作:
if (ca.Exception != null)
{
var ignoreTask = Task.Run(() => _logger.LogException(LogLevel.Error, ca.Exception.Message, ca.Exception));
}
您正在线程池线程上启动新任务,而不是等待该任务。将
LogException
代码块放在 try
/catch
块中以忽略引发的任何异常。