Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is CreateDirectory() in C# thread-safe?

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?

Note that according to MSDN, it is OK to call CreateDirectory() on a directory which already exists, in which case the method is expected to do nothing.

like image 957
bavaza Avatar asked Mar 05 '12 19:03

bavaza


People also ask

Can you make a directory in C?

This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename.

What does mkdir return in C?

RETURN VALUEUpon successful completion, mkdir() shall return 0. Otherwise, -1 shall be returned, no directory shall be created, and errno shall be set to indicate the error.

How do you create a file in C?

To create a file in a 'C' program following syntax is used, FILE *fp; fp = fopen ("file_name", "mode"); In the above syntax, the file is a data structure which is defined in the standard library. fopen is a standard function which is used to open a file.

How does chdir work?

The chdir command is a system function (system call) which is used to change the current working directory. On some systems, this command is used as an alias for the shell command cd. chdir changes the current working directory of the calling process to the directory specified in path.


1 Answers

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.

like image 142
JaredPar Avatar answered Oct 06 '22 20:10

JaredPar