C# 进程无法访问此文件,因为c中的另一个进程正在使用它#

C# 进程无法访问此文件,因为c中的另一个进程正在使用它#,c#,multithreading,locking,streamwriter,C#,Multithreading,Locking,Streamwriter,我尝试使用1个锁对象,并尝试在锁下的两个不同位置使用StreamWriter写入同一个文件,但出现错误: 进程无法访问文件“filename”,因为其他进程正在使用该文件 锁定对象定义,我使用静态对象: protected static Object Semaphore = new Object(); if(x != null) { lock (Semaphore) { using (StreamWriter sw = new StreamWriter(file

我尝试使用1个锁对象,并尝试在锁下的两个不同位置使用StreamWriter写入同一个文件,但出现错误:

进程无法访问文件“filename”,因为其他进程正在使用该文件

锁定对象定义,我使用静态对象:

protected static Object Semaphore = new Object();

if(x != null)
{
    lock (Semaphore)
    {
        using (StreamWriter sw = new StreamWriter(fileName))
        {

            sw.WriteLine(a + "," + b + "," + c);
            sw.Close();
            sw.Flush();
        }
    }

}
紧接着:

if(y != null)
{
    lock (Semaphore)
    {
        using (StreamWriter sw1 = new StreamWriter(fileName))
        {

            sw1.WriteLine(a + "," + b + "," + c);
            sw1.Close();
            sw1.Flush();
        }
    }
}

我错过了什么?谢谢。

您的操作系统仍将该文件标记为“正在使用”-错误消息不是来自您的信号灯机制。通常情况下,我认为信号量与using结合使用应该永久关闭文件

两个代码部分中的哪一个会引发异常?你在别的地方打开过吗

顺便说一句,请复制粘贴/修复您的代码-粘贴的演示代码将不会运行-关闭的文本编写器无法刷新

我的测试用例-尚未线程化:

internal class Program
{
    public static void DoStuff()
    {
        Directory.CreateDirectory(Path.GetDirectoryName(fileName));

        if (x != null)
        {
            lock (lockObj)
            {
                WriteStuff();
            }
        }

        if (y != null)
        {
            lock (lockObj)
            {
                WriteStuff();
            }
        }
    }


    private static string fileName = "C:\\temp\\tempfile.txt";
    private static object lockObj = new object();
    private static string x = "";
    private static string y = "";

    static void Main(string[] args)
    {
        DoStuff();
    }

    static void WriteStuff()
    {
        using (StreamWriter sw1 = new StreamWriter(fileName))
        {
            sw1.WriteLine("irrelevant");
        }
    }
}

你需要展示你是如何使用这段代码的,因为这是最重要的部分。在这段代码中不需要关闭和刷新。使用将处理streamwriter,这将刷新并关闭它。您确实需要为我们提供一个解决方案,以便我们看到此问题的实际效果。现在你的代码看起来很棒,所以我们无法回答。