C#线程池应用程序在web应用中是否继续执行的测试

线程池线程在进程未结束时,做为后台线程,它不会结束执行。但在前台进程结束后,没有执行完成的线程池对象就不会再执行了。因此做为web应用程序,使用线程池线程可能增加性能。但要考虑如果进程结束了。程序是否会被terminate的问题。

首先做了在应用程序池的测试。使用iis新建了一个网站。然后打开页面。用ajax去调用方法。然后迅速关闭该页面。ajax的方法如下:

 private void ThreadPoolTest()
        {
            /*测试目的是当页面关闭后,在线程池中的程序是不是仍可能运行*/
            logger.Debug("this is a test!");
            commResponse.IsSuccess = true;
            commResponse.Msg = "返回数据成功";
            ThreadPool.QueueUserWorkItem((obj) => {
                logger.Debug("threadPool is start ....");
                Thread.Sleep(1000 * 30);
                logger.Debug("threadPool is end!");
            });
            ReturnJson(commResponse);
        }

测试结果如下:由此可以在部署后的web应用程序中这个进程池一直在运行的,所以它没有被结束掉。

2018-09-08 22:33:27,916 [9] DEBUG WebDemo.Ajax.ComsumerAjax - this is a test!
2018-09-08 22:33:27,937 [8] DEBUG WebDemo.Ajax.ComsumerAjax - threadPool is start ....
2018-09-08 22:33:57,937 [8] DEBUG WebDemo.Ajax.ComsumerAjax - threadPool is end!

接下来,思考如果使用VS中的服务启动,ajax后迅速结束服务。会出现什么情况呢?

 private void ThreadPoolTest()
        {
            /*测试目的是当页面关闭后,在线程池中的程序是不是仍可能运行*/
            logger.Debug("this is debug mode's test!");
            commResponse.IsSuccess = true;
            commResponse.Msg = "返回数据成功";
            ThreadPool.QueueUserWorkItem((obj) => {
                logger.Debug("threadPool is start ....");
                Thread.Sleep(1000 * 30);
                logger.Debug("threadPool is end!");
            });
            ReturnJson(commResponse);
        }

结果如下:

2018-09-08 22:33:27,916 [9] DEBUG WebDemo.Ajax.ComsumerAjax - this is a test!
2018-09-08 22:33:27,937 [8] DEBUG WebDemo.Ajax.ComsumerAjax - threadPool is start ....
2018-09-08 22:33:57,937 [8] DEBUG WebDemo.Ajax.ComsumerAjax - threadPool is end!
2018-09-08 22:36:57,588 [7] DEBUG WebDemo.Ajax.ComsumerAjax - this is debug mode's test!
2018-09-08 22:36:57,595 [6] DEBUG WebDemo.Ajax.ComsumerAjax - threadPool is start ....

结论:

在IIS环境下部署的web应用,因为进程在持续的进行的,所以可以放心地使用线程池来处理一些简短的任务。下一篇中我们继续探讨在windows服务中,是不是也可以安全地使用线程池来完成任务呢?

猜你喜欢

转载自blog.csdn.net/pengdayong77/article/details/82534270
今日推荐