C# 作为windows服务运行的多线程控制台应用程序(使用Topshelf)

C# 作为windows服务运行的多线程控制台应用程序(使用Topshelf),c#,.net,multithreading,console-application,worker,C#,.net,Multithreading,Console Application,Worker,我正在尝试创建一个windows服务,它定期监视文件夹,如果文件夹中有新文件,它可以为文件夹触发PowerShell脚本(脚本可以处理每个事件的其余工作) 到目前为止,我已经创建了一个C#console应用程序,它使用TopShelf(便于调试并将其作为服务运行),但它只能执行一个操作 我要寻找的是,如果一个事件发生,它会触发脚本并让它运行直到完成(或失败),但同时在该文件夹中的循环运行期间有另一个事件,它应该能够生成另一个线程来运行该脚本的另一个副本 while(True): if file

我正在尝试创建一个windows服务,它定期监视文件夹,如果文件夹中有新文件,它可以为文件夹触发PowerShell脚本(脚本可以处理每个事件的其余工作)

到目前为止,我已经创建了一个C#console应用程序,它使用TopShelf(便于调试并将其作为服务运行),但它只能执行一个操作

我要寻找的是,如果一个事件发生,它会触发脚本并让它运行直到完成(或失败),但同时在该文件夹中的循环运行期间有另一个事件,它应该能够生成另一个线程来运行该脚本的另一个副本

while(True):
if file exist:
   Run "Script.ps1"
但我想要的是,如果在循环迭代之后,它发现了多个文件,那么它会为每个文件进一步处理生成一个单独的线程

while(True):
if file exist:
thread1 -> run script.ps1 (for 1st file)
thread2 -> run script.ps1 (for 2nd file)
.
.
.
threadn -> run script.ps1 (for nth file)

n个文件数n个线程数(可以强制执行限制,如10)

到目前为止,我已经创建了一个类,但如果只有一个作业,它所做的一切都是一样的

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Packaging
{
    public class Fileextractor
    {
        private readonly Timer _timer;

        public Fileextractor()
        {
            _timer = new Timer(5000) { AutoReset = true };
            _timer.Elapsed += TimerElapsed;

        }

        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
           // find file in folder
           // if file exist
              // run script.ps1

        }

        public void Start()
        {
            _timer.Start();

        }

        public void Stop()
        {
            _timer.Stop();

        }
    }
}


不完全清楚你在寻求什么帮助。如果你只是想衍生出一个新的线程,这很容易。只需使用:


我可以将其与现有代码集成吗?
ThreadPool.QueueUserWorkItem(_ =>
{
   // your code that will run on a separate thread here
});