如何通过使用 C#.NET 传递参数来设置动态线程的计时器
本文关键字:设置 动态 线程 计时器 参数 何通过 NET | 更新日期: 2023-09-27 18:37:07
嗨,我
正在使用一个具有动态线程生成逻辑的窗口服务应用程序,该应用程序将用于为每个单独的属性ID创建一个单独的基于线程的XML文件获取数据,现在我担心的是我想以不同的时间间隔运行这些每个线程,一个线程使用每5分钟触发一次, 另一个线程用于每天触发模式,最后一个线程应该按月方式触发,你能帮帮我,可能是我在想什么,当我启动一个窗口服务时,所有的线程都要启动,这些生成的线程即使暂时工作完成也不应, 我们需要根据上面我说的为这些线程设置一个计时器,我们如何执行这个善意的建议......
下面我粘贴了相同的动态线程逻辑代码:
我想知道如何为每个不同的线程设置计时器
static void Main(string[] args)
{
var currentDir = Directory.GetCurrentDirectory();
var xDoc = XDocument.Load(string.Format(Path.Combine(currentDir, "Hosts.xml")));
var threads = new List<Thread>();
foreach (XElement host in xDoc.Descendants("Host"))
{
var hostID = (int)host.Attribute("id");
var extension = (string)host.Element("Extension");
var folderPath = (string)host.Element("FolderPath");
var thread = new Thread(DoWork)
{
Name = string.Format("samplethread{0}", hostID)
};
thread.Start(new FileInfo
{
HostId = hostID,
Extension = extension,
FolderPath = folderPath
});
threads.Add(thread);
}
// Carry on with your other work, then wait for worker threads
threads.ForEach(t => t.Join());
}
static void DoWork(object threadState)
{
var fileInfo = threadState as FileInfo;
if (fileInfo != null)
{
// Do stuff here
}
}
class FileInfo
{
public int HostId { get; set; }
public string Extension { get; set; }
public string FolderPath { get; set; }
}
您的线程将运行,然后再次停止。已停止的线程无法再次启动。您需要某种类型的循环来保持线程运行。
这是对代码的修改,我在其中编写了一个类来围绕您的DoWork函数包装这样的循环:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Threading;
namespace App
{
class FileInfo
{
public int HostId { get; set; }
public string Extension { get; set; }
public string FolderPath { get; set; }
}
class ThreadSet
{
public ThreadStart action;
public FileInfo file;
public string name;
public Boolean shouldrun = true;
public Thread thread;
public ThreadSet(XElement host, Action<Object> threadaction)
{
int hostID = (int)host.Attribute("id");
name = string.Format("samplethread{0}", hostID);
file = new FileInfo
{
HostId = hostID,
Extension = (string)host.Element("Extension"),
FolderPath = (string)host.Element("FolderPath")
};
action = () =>
{
while (shouldrun)
{
threadaction(file);
}
};
thread = new Thread(action);
thread.Name = name;
}
public void Start()
{
thread.Start();
}
public void Join()
{
shouldrun = false;
thread.Join(5000);
}
}
class Program
{
static void Main(string[] args)
{
var currentDir = Directory.GetCurrentDirectory();
var xDoc = XDocument.Load(string.Format(Path.Combine(currentDir, "Hosts.xml")));
var threads = new List<ThreadSet>();
foreach (XElement host in xDoc.Descendants("Host"))
{
ThreadSet set = new ThreadSet(host, DoWork);
set.Start();
threads.Add(set);
}
//Carry on with your other work, then wait for worker threads
threads.ForEach(t => t.Join());
}
static void DoWork(object threadState)
{
var fileInfo = threadState as FileInfo;
if (fileInfo != null)
{
//Do stuff here
}
}
}
}