Is CreateDirectory() in C# thread-safe?

后端 未结 3 1534
鱼传尺愫
鱼传尺愫 2021-02-07 12:01

Can I safely attempt to create the same directory from two different threads, without having one of them throw an exception, or run into other issues?

3条回答
  •  暖寄归人
    2021-02-07 12:54

    The Directory.CreateDirectory call itself is safe to make from multiple threads. It will not corrupt program or file system state if you do so.

    However it's not possible to call Directory.CreateDirectory in such a way to guarantee it won't throw an exception. The file system is an unpredictable beast which can be changed by other programs outside your control at any given time. It's very possible for example to see the following occur

    • Program 1 Thread 1: Call CreateDirectory for c:\temp\foo and it succeeds
    • Program 2 Thread 1: Removes access to c:\temp from program 1 user
    • Program 1 Thread 2: Call CreateDirectory and throws due to insufficient access

    In short you must assume that Directory.CreateDirectory, or really any function which touches the file system, can and will throw and handle accordingly.

提交回复
热议问题