简体   繁体   中英

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

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

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

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. 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.

thread.Join();

Have you considered using asynchronous feature of C# 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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