Link to home
Start Free TrialLog in
Avatar of GrupoLayerdev
GrupoLayerdevFlag for Brazil

asked on

Problems Parallel For with StreamWriter

Hello,

Implemented Parallel.For as a test on a project I'm developing on a Windows Services.

I'm having some problems because the service scans a SQL database table and returns aproximadamento some 2 million records, then it performs some actions and finally it writes the result of operation fied in a text file.

Looking at the text file I realized that it works well but some records are compromised because some threads try to write the file while the value of the record is wrong.

How can I do to allow a result to be written on the bench only after a thread may have finished writing?

It is worth observing that I'm using a server with 16 processing cores.

Part code:

FileStream fs = new FileStream("C:\\Logs\\001_log.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
StreamWriter fp = new StreamWriter(fs);
Parallel.For(0, table.Rows.Count, (k) =>
{
    try
    {
        Int32 iReturn = ProcRegister((Int32)table.Rows[0][0]);
        fp.WriteLine(iReturn);
        fp.Flush();
    }
    catch{}
    finally{}
});

fp.Close();
fp.Dispose();
fs.Dispose();
fs.Close();




Part of the log file with problem:

...
985217
991848
985680
988684
989989
983342
7367  983342 <---
7367  983342 <---
7367         <---
984540
986244
986016
984964
991237
...

Regards,
ASKER CERTIFIED SOLUTION
Avatar of GrupoLayerdev
GrupoLayerdev
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial