如何多次运行一个后台工作程序 [英] How can I run one background worker for multiple times

查看:166
本文介绍了如何多次运行一个后台工作程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

后台工作人员读取txt文件并将其写入mssql服务器。

我想多次使用一个后台工作者。

有很多文件和一个backgroundworker不足以读取文件,花了很多时间。



你有什么想法吗?



我尝试了什么:



没有什么特别谷歌搜索不等等。

Background worker does read the txt files and write it to mssql server.
I want to use one backgroundworker for multiple times.
There are lots of files and one backgroundworker is not enough for read files, its took lots of time.

Do you have any idea?

What I have tried:

nothing for special google searcing not etc.

推荐答案

看看这个功能,这很简单:



如何:编写一个简单的Parallel.ForEach循环Microsoft Docs [ ^ ]



在这种情况下,您根本不需要任何明确创建的工作线程!
Take a look at this feature, that is realy simple:

How to: Write a Simple Parallel.ForEach Loop | Microsoft Docs[^]

In this case you don't need any explicit created Worker Thread at all!


做的时要小心使用并行编程的磁盘I / O,特别是在使用硬盘时。

大部分时间这比顺序执行要慢!
Be careful when doing disk I/O using parallel programming, especially when using a harddisk.
Most of the time this will turn out slower than doing things sequentially !


BackgroundWorker是本质上是一个线程 - 所以你不想多次运行一个worker,你想在同一个代码上运行多个worker。这很容易做到:只需为每个文本文件创建一个新的BackgroundWorker,并为每个实例传递一个不同的文件进行处理。您需要的只是文件的循环,以及其中现有代码的副本:

A BackgroundWorker is essentially a thread - so you don't want to run one worker multiple times, you want to run multiple workers on the same code. That's easy to do: just create a new BackgroundWorker for each text file and pass each instance a different file to process. All you need for that is a loop for the files, and a copy of your existing code inside it:
foreach (string file in files)
   {
   BackgroundWorker work = new BackGroundWorker();
   ...
   work.RunWorkerAsync(file);
   }

然后,您可以从DoWork事件处理程序中的e.Argument属性中获取文件。

You can then pick up the file from the e.Argument property inside the DoWork event handler.


这篇关于如何多次运行一个后台工作程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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