如何根据文件数创建多个线程? [英] How do I create multiple threads based on number of files ?

查看:160
本文介绍了如何根据文件数创建多个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了太多这个特定的问题。我想要做的是从文件DialogBox中读取多个文件,我想根据用户在文件DialogBox中选择的文件数创建线程数,即如果用户选择了2线程然后我应该只创建2个线程,每个单独的线程应该并行处理单个文件。这可能吗?



我尝试过的事情:



我有创建了一个文件对话框。我正在文件对话框中读取这些文件,并在读取这些文件时应用了锁。但是我没有得到如何为多个线程并行运行它。

解决方案

你必须遍历文件集合并且必须为每个文件创建新线程您想要处理。



详情请见:

线程(C#)| Microsoft Docs [ ^ ]

多线程应用程序(C#)| Microsoft Docs [ ^ ]

演练:使用BackgroundWorker组件进行多线程处理(C#) Microsoft Docs [ ^ ]


Quote:

如果用户选择了2个线程,那么我应该只创建2个线程,每个单独的线程应该并行处理单个文件。这可能吗?

我假设你的意思是:如果用户选择2 文件那么我应该创建2个线程。每个线程必须处理一个文件。是否可能?

是的,当然可以。

我建议你在 C#上阅读多任务教程。


我不知道你的理由对于指定1个文件= 1个线程,可能有一个很好的理由。

但是如果你的理由只是在后台执行文件处理而不妨碍UI线程,请调查使用async / await执行耗时的I / O东西。

离开用户界面&响应

I have googled too much for this particular problem .What am trying to do is reading the multiple files from file DialogBox and I want to create number of threads based on number of files selected by user in file DialogBox i.e. if user has selected 2 threads then I should create 2 threads only and each indivisual thread should process the single file parallerly. Is this possible ?

What I have tried:

I have created a file dialog box . I am reading those files in file Dialog box and applied Lock on reading those files . But am not getting how do I run it parallely for multiple threads.

解决方案

You have to loop through the collection of files and have to create new thread for every single file you want to process.

For further details, please see:
Threading (C#) | Microsoft Docs[^]
Multithreaded Applications (C#) | Microsoft Docs[^]
Walkthrough: Multithreading with the BackgroundWorker Component (C#) | Microsoft Docs[^]


Quote:

if user has selected 2 threads then I should create 2 threads only and each indivisual thread should process the single file parallerly. Is this possible ?

I assume you meant: "if the user selects 2 files then I should create 2 threads. Each thread must process a file. Is it possible?"
Yes, it is possible of course.
I suggest you reading a tutorial on multitasking in C#.


I don't know your reason for specifying 1 file = 1 thread, maybe there's a good reason for it.
But if your reason is just to perform file processing in the background without encumbering the UI thread, investigate using async/await to perform the time-consuming I/O stuff.
Leaving the UI free & responsive.


这篇关于如何根据文件数创建多个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆