简体   繁体   English

如何在.NET中以更好的方式使用并行线程(TPL)

[英]How to use parallel threading (TPL) in a better way in .NET

I am using .net framework 4.0, and I have number of text files stored in some places in a server .What i am doing now is pushing data from text files to oracle database.I have created four threads to process text files and all are accessing different text files , not same files.and more over third method t3 should happen after second t2 and only after the completion of four methods pushing in to the database, i am exporting data based on different algorithm which should happen after completion four threads.So i have a few questions here 我正在使用.net Framework 4.0,并且我在服务器的某些位置存储了许多文本文件。我现在正在做的是将数据从文本文件推送到oracle数据库。我创建了四个线程来处理文本文件,所有线程访问不同的文本文件,而不是相同的文件。第三种方法t3应该在第二种t2之后发生,并且只有在完成将四种方法推入数据库之后,我才根据不同的算法导出数据,这应该在完成四个线程之后发生。所以我在这里有几个问题

1.I am using .net framework 4.0 ,Is there any chance of missing the completion of processing files in to database by using the following code.Is there any better way 1.我使用的是.net framework 4.0,是否有可能通过使用以下代码来丢失对数据库中文件处理的完成。是否有更好的方法

2.Does task t2 will happen before t3, is there any chance of missing processing of files? 2.任务t2是否会在t3之前发生,是否有丢失文件处理的机会?

static void Main(string[] args)
{
    Task t1 = Task.Factory.StartNew(() => {
        FirstmethodPushtodatabase();
    });
    Task t2 = Task.Factory.StartNew(() => {
        SecondmethodPushtodatabase();
    });
Task.WaitAll(t2);
 Task t3 = Task.Factory.StartNew(() => {
        ThirdmethodPushtodatabase();
    });
 Task t4 = Task.Factory.StartNew(() => {
        FourthmethodPushtodatabase();
    });

    Task.WaitAll(t1, t2,t3,t4);
    Thirdmethod();
    Console.ReadLine();
}

EDIT which is best here? 编辑这是最好的吗? creating seperate process or threads? 创建单独的进程或线程?

You won't be missing any work of pushing data in to the database. 您将不会丢失任何将数据推入数据库的工作。 However a better approach to sequence tasks would be to use Task.ContinueWith . 但是,对任务进行排序的更好方法是使用Task.ContinueWith You can read more on this on MSDN Task.ContinueWith 您可以在MSDN Task.ContinueWith上阅读更多内容。

Principally you could do this to sequence t2 and t3 原则上,您可以对t2和t3进行排序

Task t2 = Task.Factory.StartNew(() => {
    SecondmethodPushtodatabase();
}).ContinueWith(
    (t) => {
    ThirdmethodPushtodatabase(); }
);

This will allow T4 to begin simultaneously with the other tasks. 这将使T4与其他任务同时开始。

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

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