• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 723
  • Last Modified:

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,
0
GrupoLayerdev
Asked:
GrupoLayerdev
1 Solution
 
GrupoLayerdevAuthor Commented:
I'm solve the problem.


FileStream fs = new FileStream("C:\\Logs\\001_log.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);

Object locker = new Object()

StreamWriter fp = new StreamWriter(fs);

Parallel.For(0, table.Rows.Count, (k) =>
{
    try
    {
        Int32 iReturn = ProcRegister((Int32)table.Rows[0][0]);
        lock (locker)
        {
            fp.WriteLine(iReturn);
            fp.Flush();
        }
    }
    catch{}
    finally{}
});

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

Open in new window

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now