Multithreading 任务并行库与Windows服务

Multithreading 任务并行库与Windows服务,multithreading,windows-services,task-parallel-library,Multithreading,Windows Services,Task Parallel Library,我有以下要求 一个asp.net网站,并根据登录的用户请求,它将在后台启动一个windows服务(从代码运行windows服务)。即使用户从该站点注销,该服务仍将继续运行 同时,任何数量的登录用户都可以运行该服务(服务中的代码基于登录用户id更新数据库)。因此,为了实现这一点,我使用了TPL(任务并行库),并在我的windows服务“OnCustomCommand”事件中创建了任务。这意味着,如果有10个用户调用该服务,10个任务将被装箱 请注意,我使用了TPL“TaskCreationOpti

我有以下要求

一个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 
        }
受保护的覆盖void OnCustomCommand(int命令)
{
如果(命令==1)
{
if(threadCount<10)//这里我将检查已经创建的线程数,
//如果小于10,则只会创建一个新任务,并通过新线程执行。
//否则,请求将在队列中,当一个任务完成时,它将减少线程数。
{
Task t=Task.Factory.StartNew(()=>
{
ThreadProcedure();
},TaskCreationOptions.LongRunning);
}
}
}
私有虚线程过程()
{
threadCount++;//将更新线程数并保存
//我的服务逻辑
}

谢谢。

那么为什么要使用long running?@Dev您只访问数据库并在线程内更新它吗?或者线程也用于调用windows服务?@I3arnon-->windows服务中的代码需要10-12小时才能完成。用户无法登录站点的时间太长。这就是为什么我使用windows服务概念在后台执行任务的原因。@Yuval-->这不仅仅是访问数据库并更新它。还有一些复杂的逻辑,使得服务运行很长时间。它实际上是从另一个大数据库提取数据。线程不用于调用windows服务。在windows服务内部使用线程来执行长时间运行的任务。我使用线程的概念是因为请求来自多个用户。因此,对于每个请求,一个线程将处理它。即使我限制了要同时创建的线程数。