问题
I'm catching and logging exceptions in an ASP.NET Web API 2 app by starting a new thread to log:
void MainMethod(){
try{
// stuff...
} catch (Exception ex) {
Logger.Log(ex);
}
}
class Logger {
void Log(Exception ex) {
Task.Factory.StartNew(() => LogAsync(ex));
}
void LogAsync(Exception ex) {
// doing some reflection stuff to retrieve code-place
// saving the log...
}
}
The question is: in a real high traffic app, does this approach has any side effects? Is it better to log in the main context?
P.S. The question is related to this one.
回答1:
in a real high traffic app, does this approach has any side effects?
That will usually depend on the environment you're running in, what your hardware is, and what "real high traffic" actually means.
In general, using a new thread to simply log might produce more overhead than the actual gain of "freeing up" the current thread to do more work. Yes, it will use the same threads used by the ASP.NET ThreadPool, and if it gets called frequently, you might be causing starvation to your pool, although that is unlikely.
More over, using Task.Factory.StartNew
is ASP.NET is dangerous because it doesn't register the work offloaded to that thread with IIS.
IMO, You should keep it simple and log synchronously.
来源:https://stackoverflow.com/questions/29578284/does-task-factory-startnew-has-any-performance-side-effects