Is new Thread(() => {//logic}).Start(); acceptable for executing logic "asynchronously" in web apps page_load
(I use the term "asynchronously" loosely in the subject)
I've been using the b开发者_C百科elow code for a while to save initial session context info to the DB such as affiliate details for later tracking. I've suggested others to use this concept to speed up some of their processes but i'd hate to be suggesting something that is potentially dangerous.
I'd like to know if this is acceptable or are there some threading issues i'll be causing later down the road on peak traffic times?
new Thread(() => {
//All my logic for saving info to DB
})
{ Name = "My long running page process", IsBackground = true, Priority = ThreadPriority.Normal }.Start();
UPDATE
Thanks! After David Basarab's answer, I think this will be my new method:
Action someLongProcess = () =>
{
// You DB Work
};
someLongProcess.BeginInvoke((x) => {
someLongProcess.EndInvoke(x);
// It is now done you can do something
}, null);
I would use the thread pool. Because it gives uses a predefeined pools of threads, rather than create a new one for each request. And it gives you the true Async by exposing a callback.
You can just use the Action delegate and call the BeginInvoke which uses the thread pool in the background.
Action someLongProcess = () =>
{
// You DB Work
};
AsyncCallback callback = (r) =>
{
// It is now done you can do something or pass null to do nothing
};
someLongProcess.BeginInvoke(callback, null);
No, it may work but it is barely acceptable. Creating a Thread takes time, so this will usually make your performance worse.
Use the ThreadPool or (Fx 4+) the Task library.
The ThreadPool would be a better choice. But I recommend reading Make methods “fire and forget” with PostSharp, which gives alternatives to using Thread.Start.
I recommend a Task
object, or ThreadPool
if Task
is not available. However, one thing you need to watch out for is recycling. Background threads can be unexpectedly terminated in this situation.
If you have data that needs to be saved to the database, I'd recommend async pages and using AsyncOperation
(or BackgroundWorker
, which uses AsyncOperation
underneath).
Using the ThreadPool
should be preferred, as it requires less resources.
ThreadPool.SetMaxThreads(4);
ThreadPool.QueueUserWorkItem(state => { Trace.WriteLine("Hello World."); });
The overhead for a new thread in .NET is actually quite high, stack pages of the new thread are actually commited and not only reserved, see the discussion in the comments here and this blog post.
精彩评论