简体   繁体   中英

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

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

2.Does task t2 will happen before t3, is there any chance of missing processing of files?

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 . You can read more on this on MSDN Task.ContinueWith

Principally you could do this to sequence t2 and t3

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

This will allow T4 to begin simultaneously with the other tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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