-1

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

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

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

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();

        }
    }
}

4

1 回答 1

1

不完全清楚你在寻求什么帮助。如果您只想分拆一个新线程,这很容易。只需使用ThreadPool.QueueUserWorkItem()

ThreadPool.QueueUserWorkItem(_ =>
{
   // your code that will run on a separate thread here
});
于 2021-04-11T05:29:15.690 回答