问题
In order to optimize some server-side database calls I decided to use System.Threading.Tasks.Task to parallelize several database calls then use Task.WaitAll() to get all the results, package them up and send them to the client via WCF. This seems to work fine when testing on the dev web server in Visual Studio (cassini) but does not work when deployed to IIS. Profiling the client calls (with firebug) shows that calls get to IIS but no corresponding calls are submitted to SQL Server.
Anyone experienced this? Is there a limitation in using Tasks within IIS?
回答1:
There is no direct limitation - however, when you use a Task, it schedules the Task on the ThreadPool. IIS, by default, shares a single thread pool for the entire IIS process, which can (especially on a busy server) cause thread starvation to occur. This means that the same guidance about using the ThreadPool applies when working with tasks. See this post for details.
In order to see if this is the problem, you could, at least as a test, generate all of your Task instances with the TaskCreationOptions.LongRunning hint. This will cause the default TaskScheduler to create task on it's own, dedicated (new) Thread instead of using a ThreadPool thread. While I don't think this is a good idea for a long term solution, you would be able to verify that it's thread pool starvation causing your problem. If it is, you could determine other options, such as potentially using a custom TaskScheduler to manage the threads/tasks for this operation.
来源:https://stackoverflow.com/questions/4962039/using-tpl-task-from-wcf