Does Task.Factory.StartNew has any performance side effects?

只谈情不闲聊 提交于 2019-12-12 06:14:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!