关于如何在这种情况下在 C# 中实现线程的问题
我有这样的场景:Windows 服务在服务器上运行。大约每隔一小时,它就会读取一个日志文件并将内容保存到数据库中。 现在,将有三个文件,必须读取这些文件并将其保存到三个不同的表中。 (我将从配置文件中读取这些连接字符串等)这可以通过我知道的线程来实现。所以我想在线程中调用现有的“readfile”方法。
我不熟悉线程,但这是要走的路吗?
NameValueConfigurationCollection config = ConfigurationManager.GetSection("LogDirectoryPath") as NameValueConfigurationCollection;
foreach (DictionaryEntry keyvalue in configs)
{
Thread t = new Thread(new ThreadStart(ExecuteProcess(keyvalue.Key.ToString())));
t.IsBackground = true;
t.Start();
}
private void ExecuteProcess(string path)
{
var xPathDocument = new XPathDocument(path);
XPathNavigator xPathNavigator = xPathDocument.CreateNavigator();
string connectionString = GetXPathQuery(
xPathNavigator,
"/connectionString/@value");
string commandText = GetXPathQuery(
xPathNavigator,
"/commandText/@value");
string filePath = GetXPathQuery(
xPathNavigator,
"/filePath/@value");
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
ProcessFiles(sqlConnection, commandText, filePath);
}
我必须使方法静态吗?使用的变量怎么样?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 .NET 4 中,您可以利用任务并行库来实现此目的,因此您不必显式创建线程,而只需表达您想要并行执行的代码:
In .NET 4 you could leverage the Task Parallel Library for this, so you would not have to explicitly create threads, but just express what code you want to execute in parallel:
我个人偏好是使用 ThreadPool对于我希望在即发即忘场景中并行运行的线程,例如
并行任务库也很有用,但不能保证并行,而是处理器的数量。但是,它确实会再次同步所有工作线程。所以这取决于你想要实现什么目标
My personal preference is to use ThreadPool for threads which I wish to run in parallel in a fire and forget scenario e.g. something like
The Parallel Task library is also useful but not guaranteed to go parallel and instead adapts, as I understand it, to the number of processors. It does however synchronise all your worker threads back again. So it depends on what it is you are trying to achieve,