ASP.NET - 写入同一文件的不同线程导致问题

0 c# asp.net locking

我有一个执行删除和创建文件的方法.所有线程都试图同时访问该文件存在问题.

如何限制对文件的访问?

public static Save(string file)
{
  //1.Perform Delete
  //2.Perform Write 
}
Run Code Online (Sandbox Code Playgroud)

请注意,该方法是静态的,因此可以在静态方法中锁定进程吗?

干杯

Dar*_*rov 6

private static readonly object _syncRoot = new object();
public static void Save(string file)
{
    lock(_syncRoot) {
        //1.Perform Delete
        //2.Perform Write 
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用MethodImplAttribute来放置lock整个方法体:

[MethodImpl(MethodImplOptions.Synchronized)]
public static void Save(string file)
{
    //1.Perform Delete
    //2.Perform Write 
}
Run Code Online (Sandbox Code Playgroud)