简体   繁体   English

C#和多线程逻辑

[英]C# and multithreading logic

What i am trying to do is create a function that reads all the content of file and regex something. 我想要做的是创建一个函数,读取文件和正则表达式的所有内容。 What i have done so far is created a function 到目前为止我所做的是创造了一个功能

read_content(string filename); read_content(string filename);

but before this function i ask user to choose a directory and then read all the names of file present in there 但在此功能之前,我要求用户选择一个目录,然后读取其中存在的所有文件名

DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo file in dir.GetFiles())
{
save in array
}

and i have started a thread 我已经开始了一个主题

 var t = new Thread(() => read_content(filename));
  t.Start();

This is all working fine, now i want to make it multi thread, right now its single thread 这一切都运行正常,现在我想让它成为多线程,现在它的单线程

i want a user to enter like start 10 thread and these threads read one file at a time ultil reaches to end 我希望用户输入类似start 10线程,这些线程一次读取一个文件ultil到达结束

I tried searching on google but could not find like my need, i dont want whole code just tell me logic or some basic code, want to learn and code on my own 我尝试在谷歌搜索,但找不到我的需要,我不想要整个代码只是告诉我逻辑或一些基本代码,想要自己学习和编码

EDIT: Seems like i have more vote for threadpool, soo a link to good tut would be appreciated 编辑:似乎我有更多的投票为线程池,所以赞赏良好的tut链接

You can use the Task Parallel Library . 您可以使用任务并行库

You shouldn't set the amount in threads by hand - you should let the system take care of this. 您不应该手动设置线程数量 - 您应该让系统处理这个问题。 The TPL does this for you, so just create the tasks, and they will be executed eventually. TPL为您完成此任务,因此只需创建任务,它们最终将被执行。 Usually, one task per core is executed (not sure though). 通常,每个核心执行一个任务(但不确定)。

Your code could be like: 你的代码可能是这样的:

DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo file in dir.GetFiles()) {
    var filename = file.FullName;
    new Task(() => {
        read_content(filename);
    }).Start();
}

Note: your code doesn't check when the thread is finished, so I haven't included this either. 注意:您的代码不会检查线程何时完成,因此我也没有将其包括在内。 If you want this, you have to keep the tasks in a list, and check if the tasks have finished. 如果需要,您必须将任务保留在列表中,并检查任务是否已完成。

您可以使用ThreadPool类并在每个文件上调用File.ReadAlltext (:

Use 采用

ThreadPool.QueueUserWorkItem(<method>, <obj_arg>);

This will reuse the threads and won't create thread for every file. 这将重用线程,不会为每个文件创建线程。 You can perform Join at the end of the foreach. 您可以在foreach结束时执行Join。

thread.Join();

Have you considered using asynchronous feature of C# 5 您是否考虑过使用C#5的异步功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM