Matthew Rathbone
Matthew Rathbone

Reputation: 8269

Can I safely spawn threads in ASP.NET MVC?

I have a scheduled task that I need to kick off by browsing to a page, my webhost doesn't allow me to use the windows scheduler.

One job this task performs is to get some data from a bunch of other websites, due to how slow web-requests can be I've set up the task to use threading.

Running this task from an mvc action seems to cause the whole webserver to go wacky, making it refuse to load any more pages.

Is it bad to use threading from a web-app? Is there a way for me to safely do it? What threading limits are there? I really just need to know some more information?

EDIT: SUBQUESTIONS

If I use threads from the threadpool (which is used by the ASP.NET runtime (thanks Anton), can I limit how many of the threads it can use? What is the ASP.NET threadpool size limit?

Would be be better to have a separate site which does this? Perhaps a virtual folder containing a separate ASP.NET application? That would stop me from limiting the threadpool right?

Upvotes: 3

Views: 2496

Answers (3)

Anton Gogolev
Anton Gogolev

Reputation: 115907

When servicing incoming requests, ASP.NET runtime acquires threads from .NET ThreadPool, which has limited capacity. So if you're using threads from that tread pool, this may harm your applications' scalability.

The way around this will be spawning a usual Thread, but these can be killed when your AppPool gets recycled.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1064324

I would be surprised if it actively caused a problem, as long as those threads don't try to talk back to the request/response (which may now be gone). What symptoms are you seeing? Can you define "wacky"?

I use threads routinely for logging etc, without issue.

To minimise the impact, you could use a producer/consume pattern, so you only have one (or a few) worker threads, servicing however-many ASP.NET MVC request/response threads.

Upvotes: 3

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

I think it depends on how it is done. I am not terribly competent when it comes to threading under ASP.NET, but I think that there is a risk that you end up using threads that would otherwise be used to serve requests from clients.

Here is a tutorial on multithreading in ASP.NET, that might help you forward a bit.

Upvotes: 0

Related Questions