打开共享写入文件

时间:2022-06-11 00:04:19

The following code is just a simplified example to demonstrate my problem:

以下代码只是一个简单的示例来演示我的问题:

using System;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication5
{
    class Program
    {
        static string LogFile = @"C:\test.log";

        static void Main(string[] args)
        {
            for (int i = 0;i<10;i++)
            {
                new Thread(new ParameterizedThreadStart(DoWork)).Start(i);
            }
            Console.ReadKey();
        }

        static void DoWork(object param)
        {
            int count = (int)param;

            try
            {
                using (FileStream fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(DateTime.Now + " - Start " + count.ToString());
                    Thread.Sleep(2000); // simulate doing some work
                    sw.WriteLine(DateTime.Now + " - End " + count.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(count.ToString() + ": " + e.Message);
                return;
            }
            Console.WriteLine(count.ToString() + ": Done.");
        }
    }
}

The problem here is that typically only one entry makes it into the file, even though I call the method 10 times. The file should be open to allow sharing. As far as I can tell no exceptions are thrown. What's going on?

这里的问题是,即使我将方法调用10次,通常只有一个条目进入文件。该文件应该是打开的以允许共享。据我所知,没有例外。这是怎么回事?

In the real code that this example shadows, each call to DoWork is actually in a separate process, though testing shows that the results are the same-- if I can fix it here I can fix it there.

在本示例影响的实际代码中,每次调用DoWork实际上都是在一个单独的进程中,尽管测试显示结果是相同的 - 如果我可以在这里修复它,我可以在那里修复它。

2 个解决方案

#1


4  

There is nothing strange going on here. Imagine that you have a file "a.txt" and you open it in notepad 10 times. After that, you change the contents of the file and save it in every instance of notepad. Naturally, the last save you make is the one that is persisted to the file because it rewrites the previous 9 saves.

这里没什么奇怪的。想象一下,你有一个文件“a.txt”,你在记事本中打开它10次。之后,您可以更改文件的内容并将其保存在记事本的每个实例中。当然,您最后保存的是保存到文件的保存,因为它会重写之前的9次保存。

I think you've got the same behavior here. All the files are opened at the same time because you have a Thread.Sleep in each processing. So the i file to be saved overwrites the previous save (i-1).

我想你在这里也有同样的行为。所有文件都是同时打开的,因为每次处理都有一个Thread.Sleep。因此要保存的i文件将覆盖先前的保存(i-1)。

EDIT: Try removing the Thread.Sleep(2000) and you'll have more logs in the file.

编辑:尝试删除Thread.Sleep(2000),你将在文件中有更多的日志。

#2


1  

Use SyncLock which makes sure only one thread opens the file at a time. In the mean time the other processes do not crash but wait in a queue.

使用SyncLock确保一次只打开一个文件。与此同时,其他进程不会崩溃,而是在队列中等待。

#1


4  

There is nothing strange going on here. Imagine that you have a file "a.txt" and you open it in notepad 10 times. After that, you change the contents of the file and save it in every instance of notepad. Naturally, the last save you make is the one that is persisted to the file because it rewrites the previous 9 saves.

这里没什么奇怪的。想象一下,你有一个文件“a.txt”,你在记事本中打开它10次。之后,您可以更改文件的内容并将其保存在记事本的每个实例中。当然,您最后保存的是保存到文件的保存,因为它会重写之前的9次保存。

I think you've got the same behavior here. All the files are opened at the same time because you have a Thread.Sleep in each processing. So the i file to be saved overwrites the previous save (i-1).

我想你在这里也有同样的行为。所有文件都是同时打开的,因为每次处理都有一个Thread.Sleep。因此要保存的i文件将覆盖先前的保存(i-1)。

EDIT: Try removing the Thread.Sleep(2000) and you'll have more logs in the file.

编辑:尝试删除Thread.Sleep(2000),你将在文件中有更多的日志。

#2


1  

Use SyncLock which makes sure only one thread opens the file at a time. In the mean time the other processes do not crash but wait in a queue.

使用SyncLock确保一次只打开一个文件。与此同时,其他进程不会崩溃,而是在队列中等待。