简体   繁体   English

如何在C#中使用多线程?

[英]How to use Multi-thread in C#?

In my project, i have to do something much much times in a foreach loop which i need to wait it about 6-7 hours. 在我的项目中,我必须在一个foreach循环中做很多事情,我需要等待大约6-7个小时。

for example: i have 80 docs to check => about 8 hours 例如:我有80个文档要检查=>大约8个小时

foreach (var doc in docs)
{
    bool valid = checkIsValid(doc); // about 2 min per doc
    if (vaid)
    {
        doThing(doc); // about 5 min per doc
    }
    else
    {
        delete(doc); // about 20s per doc
    }
}

So, i consider can i check these things in the same time which i have lots of resources is not using when running the above code. 因此,我认为我可以在运行上述代码时同时检查我有很多资源未使用的这些东西。 And i find C# has a multithread feature (i don't know what can it provides). 而且我发现C#具有多线程功能(我不知道它可以提供什么)。

Can i use it in my project? 我可以在项目中使用它吗? How to use it in my project? 如何在我的项目中使用它?

ideal: 80 docs are checking in the same time and the foreach loop will finish when 80 threads have died. 理想:80个文档同时检查,并且80个线程死亡后,foreach循环将结束。

foreach (var doc in docs)
{
    //new thread start
    bool valid = checkIsValid(doc); // about 2 min per doc
    if (vaid)
    {
        doThing(doc); // about 5 min per doc
    }
    else
    {
        delete(doc); // about 20s per doc
    }
    //thread die
}

Have you looked at Parallel.ForEach ? 你看过Parallel.ForEach吗? Your code would look like: 您的代码如下所示:

Parallel.ForEach(docs, doc => {
    if (checkIsValid(doc))
        doThing(doc);
    else
        delete(doc);
});

There are multiple ways to achieve concurrency in C# but the time taken by each method depends on the number of cores you have. 有多种方法可以在C#中实现并发,但是每种方法花费的时间取决于您拥有的内核数。 'Parallel.ForEach' is one option and probably the simplest way to achieve, but note that it will try to break your work item where possible and will speed up the execution. “ Parallel.ForEach”是一种选择,并且可能是最简单的实现方式,但是请注意,它将尽可能地破坏您的工作项目并加快执行速度。

The following code is to have multi threading but be careful 80 threads might be an overkill. 以下代码具有多线程功能,但要注意80个线程可能是一个过大的杀伤力。 So create tasks (threads) with proper consideration 因此,请适当考虑创建任务(线程)

foreach (var doc in docs)
{
    //new thread start
    bool valid = checkIsValid(doc); // about 2 min per doc
    if (vaid)
    {
        Task.Factory.StartNew(() => doThing(doc);
    }
    else
    {
        delete(doc); // about 20s per doc
    }
    //thread die
}

Tasks work in framework 4 and above 任务在框架4及更高版本中工作

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

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