任务并行库和Windows服务

时间:2014-06-18 11:45:15

标签: multithreading windows-services task-parallel-library

我有以下要求。

一个asp.net网站,根据登录的用户请求,它将在后台启动一个Windows服务(从代码运行Windows服务)。即使用户从站点注销,该服务仍将继续运行。

同时任意数量的登录用户都可以运行该服务(服务中的代码是根据登录的用户ID更新数据库)。所以为了实现这一点,我使用了TPL(任务并行库)并在我的Windows服务“OnCustomCommand”事件中,我正在创建任务。这意味着如果10个用户调用该服务,则将创建10个任务。

请注意我已经使用了TPL“TaskCreationOptions.LongRunning peoperty”作为任务长期运行。我知道如果我们设置它,它将创建一个新线程。所以我不希望100个登录用户在调用服务时使用100个线程。所以我限制了要创建的新线程的数量。

但我需要知道我是否走在正确的道路上?这是最好的方法吗?

以下是Windows服务代码和我使用的方法。 [请注意它不是确切的代码,这是我要实施的方法]

protected override void OnCustomCommand(int command)
        {
            if (command == 1)
            {
                if (threadCount < 10) // here I will check the already created threads count, 
                                      // if it is less than 10, then only will create a new task and there by new thread. 
                                      // Otherwise the request will be in queue and when one task is done it will reduce the threadcount.
                {
                    Task t = Task.Factory.StartNew(() =>
                    {
                        ThreadProcedure();
                    }, TaskCreationOptions.LongRunning);
                }

            }
        }

        private void ThreadProcedure()
        {
            threadCount++; //will update the thread count and save 
            // my service logic 
        }

感谢。

0 个答案:

没有答案