简体   繁体   English

C#中的线程执行顺序

[英]Thread execution order in c#

I have a list of thread I want to ensure the execution order between them this is the code 我有一个线程列表,我想确保它们之间的执行顺序,这是代码

for (int k = 0; k < RadioList.Count; k++)
{                                     
    for (int i = 0; i < filePaths.Count(); i++)
    {
        Thread t = new Thread(delegate()
        {                                  
            Thread_Encde_function(TempRadio.PublishPoint, filePaths[i], encodingtype);
        });
        t.Start();
        Thread.Sleep(1000);
    }
}

I want to know if thread.join() can do the job. 我想知道thread.join()可以完成这项工作。

If your tasks can execute asynchronously (out of order), then threads are appropriate. 如果您的任务可以异步执行(乱序),则线程是合适的。 However, if you have a number of tasks you want to execute in order (strictly one after the other), then why use threads? 但是,如果您要按顺序执行许多任务(严格来说是一个接一个地执行),那么为什么要使用线程? You should just execute them in your for loop, as they can't be parallelized. 您应该只在for循环中执行它们,因为它们无法并行化。 Using Thread.Join to wait for the thread right after you start it will do the trick, but that way you will have to wait until a task is finished before starting the next one, effectively executing them in order. 在启动后立即使用Thread.Join等待线程将达到目的,但是那样一来,您将必须等到任务完成后才能开始下一个任务,从而有效地按顺序执行它们。

However, if you have some parts of the tasks that can be executed simultaneously, and other parts that have to be sequential, you can take a look at the C# Task Parallel Library , it makes doing things like that easy. 但是,如果您有部分任务可以同时执行,而其他部分必须是顺序执行的,则可以看看C#Task Parallel Library ,它使执行此类操作变得很容易。

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

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